using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.IO; using System.Threading; using UnityEngine; using UnityEngine.UI; using UnityEngine.Networking; public class client : MonoBehaviour { private string staInfo = "NULL"; //状态信息 private string inputIp = "192.168.50.140"; //输入ip地址 private string inputPort = "18180"; //输入端口号 public string Message = "NULL"; //发送的消息 private int recTimes = 0; //接收到信息的次数 private string recMes = "NULL"; //接收到的消息 private Socket socketSend; //客户端套接字,用来链接远端服务器 private bool clickSend = false; //是否点击发送按钮 private bool isConnect = true; private float times = 0; private string ipPath; public Queue queueRecMsg; void Start() { ipPath = Application.persistentDataPath + "/Ipconfig/" + "ip.txt"; Debug.Log(ipPath); StartCoroutine( SettingIP()); // ClickConnect(); queueRecMsg = new Queue(); } void Update() { if(!isConnect) { times += Time.deltaTime; if(times>3f) { times = 0; ClickConnect(); } } } IEnumerator SettingIP() { yield return new WaitForSeconds(0.2f); if (File.Exists(ipPath)) { var webRequest = UnityWebRequest.Get(ipPath); yield return webRequest.SendWebRequest(); if (webRequest.error != null) { Debug.Log("通信中"); yield return webRequest; } var downloadHandler = webRequest.downloadHandler; if (!downloadHandler.isDone) { Debug.Log("下载中"); yield return downloadHandler; } else { Debug.Log("下载成功"); Debug.Log(downloadHandler.data); // if (!File.Exists(Application.dataPath + "/Resources/YourVideoName.mp4")) inputIp = System.Text.Encoding.Default.GetString(downloadHandler.data); ClickConnect(); } } else { Directory.CreateDirectory(Application.persistentDataPath + "/Ipconfig"); FileInfo fileInfo = new FileInfo(ipPath); //设置Log文件输出地址 FileStream FileWriter = fileInfo.Open(FileMode.Create, FileAccess.ReadWrite, FileShare.Read); UTF8Encoding encoding = new UTF8Encoding(); FileWriter.Write(encoding.GetBytes("192.168.50.211"), 0, encoding.GetByteCount("192.168.50.211")); FileWriter.Close(); Application.Quit(); } } //建立链接 private void ClickConnect() { Debug.Log("ClickConnect"); isConnect = true; try { int _port = Convert.ToInt32(inputPort); //获取端口号 string _ip = inputIp; //获取ip地址 Debug.Log("ClickConnect1 "+ _ip+ _port); //创建客户端Socket,获得远程ip和端口号 socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse(_ip); IPEndPoint point = new IPEndPoint(ip, _port); Debug.Log("ClickConnect2"); socketSend.Connect(point); Debug.Log("连接成功 , " + " ip = " + ip + " port = " + _port); staInfo = ip + ":" + _port + " 连接成功"; Thread r_thread = new Thread(Received); //开启新的线程,不停的接收服务器发来的消息 r_thread.IsBackground = true; r_thread.Start(); Thread s_thread = new Thread(SendMessage); //开启新的线程,不停的给服务器发送消息 s_thread.IsBackground = true; s_thread.Start(); } catch (Exception e) { Debug.LogError(e.ToString()); Debug.Log("IP或者端口号错误......"); staInfo = "IP或者端口号错误......"; isConnect = false; } } /// /// 接收服务端返回的消息 /// void Received() { while (true) { try { byte[] buffer = new byte[1024 * 6]; //实际接收到的有效字节数 int len = socketSend.Receive(buffer); if (len == 0) { // isConnect = false; break; } recMes = Encoding.UTF8.GetString(buffer, 0, len); Debug.Log("客户端接收到的数据 : " + recMes); recTimes++; staInfo = "接收到一次数据,接收次数为 :" + recTimes; // Debug.Log("接收次数为:" + recTimes); queueRecMsg.Enqueue(recMes); } catch { } } } public void SendData() { Debug.Log("sendData"); if (socketSend!=null&&SocketExtensions.IsConnected(socketSend)) { if(NetWorkLANManager.Instance.createDesMsg.Count>0) { Message = NetWorkLANManager.Instance.createDesMsg.Dequeue(); clickSend = true; return; } if(NetWorkLANManager.Instance.queueMsg.Count>0) { Message = NetWorkLANManager.Instance.queueMsg.Dequeue(); clickSend = true; } } } /// /// 向服务器发送消息 /// /// /// void SendMessage() { try { while (true) { if (clickSend) //如果点击了发送按钮 { clickSend = false; if (socketSend.Connected) { byte[] buffer = new byte[1024 * 6]; buffer = Encoding.UTF8.GetBytes(Message); socketSend.Send(buffer); // Debug.Log("发送的数据为:" + Message); } else { isConnect = false; } } } } catch { } } private void OnDisable() { Debug.Log("begin OnDisable()"); if (socketSend.Connected) { try { socketSend.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能 socketSend.Close(); //关闭Socket连接并释放所有相关资源 } catch (Exception e) { print(e.Message); } } Debug.Log("end OnDisable()"); } //用户界面 //void OnGUI() //{ // //GUI.color = Color.black; // //GUI.Label(new Rect(65, 10, 60, 20), "状态信息"); // //GUI.Label(new Rect(135, 10, 80, 60), staInfo); // //GUI.Label(new Rect(65, 70, 50, 20), "服务器ip地址"); // //inputIp = GUI.TextField(new Rect(125, 70, 100, 20), inputIp, 20); // //GUI.Label(new Rect(65, 110, 50, 20), "服务器端口"); // //inputPort = GUI.TextField(new Rect(125, 110, 100, 20), inputPort, 20); // //GUI.Label(new Rect(65, 150, 80, 20), "接收到消息:"); // //GUI.Label(new Rect(155, 150, 80, 20), recMes); // //GUI.Label(new Rect(65, 190, 80, 20), "发送的消息:"); // //Message = GUI.TextField(new Rect(155, 190, 100, 20), Message, 20); // //if (GUI.Button(new Rect(65, 270, 300, 100), "发送信息")) // //{ // // clickSend = true; // //} //} }