client.cs 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.IO;
  8. using System.Threading;
  9. using UnityEngine;
  10. using UnityEngine.UI;
  11. using UnityEngine.Networking;
  12. public class client : MonoBehaviour
  13. {
  14. private string staInfo = "NULL"; //状态信息
  15. private string inputIp = "192.168.50.140"; //输入ip地址
  16. private string inputPort = "18180"; //输入端口号
  17. public string Message = "NULL"; //发送的消息
  18. private int recTimes = 0; //接收到信息的次数
  19. private string recMes = "NULL"; //接收到的消息
  20. private Socket socketSend; //客户端套接字,用来链接远端服务器
  21. private bool clickSend = false; //是否点击发送按钮
  22. private bool isConnect = true;
  23. private float times = 0;
  24. private string ipPath;
  25. public Queue<String> queueRecMsg;
  26. void Start()
  27. {
  28. ipPath = Application.persistentDataPath + "/Ipconfig/" + "ip.txt";
  29. Debug.Log(ipPath);
  30. StartCoroutine( SettingIP());
  31. // ClickConnect();
  32. queueRecMsg = new Queue<string>();
  33. }
  34. void Update()
  35. {
  36. if(!isConnect)
  37. {
  38. times += Time.deltaTime;
  39. if(times>3f)
  40. {
  41. times = 0;
  42. ClickConnect();
  43. }
  44. }
  45. }
  46. IEnumerator SettingIP()
  47. {
  48. yield return new WaitForSeconds(0.2f);
  49. if (File.Exists(ipPath))
  50. {
  51. var webRequest = UnityWebRequest.Get(ipPath);
  52. yield return webRequest.SendWebRequest();
  53. if (webRequest.error != null)
  54. {
  55. Debug.Log("通信中");
  56. yield return webRequest;
  57. }
  58. var downloadHandler = webRequest.downloadHandler;
  59. if (!downloadHandler.isDone)
  60. {
  61. Debug.Log("下载中");
  62. yield return downloadHandler;
  63. }
  64. else
  65. {
  66. Debug.Log("下载成功");
  67. Debug.Log(downloadHandler.data);
  68. // if (!File.Exists(Application.dataPath + "/Resources/YourVideoName.mp4"))
  69. inputIp = System.Text.Encoding.Default.GetString(downloadHandler.data);
  70. ClickConnect();
  71. }
  72. }
  73. else
  74. {
  75. Directory.CreateDirectory(Application.persistentDataPath + "/Ipconfig");
  76. FileInfo fileInfo = new FileInfo(ipPath);
  77. //设置Log文件输出地址
  78. FileStream FileWriter = fileInfo.Open(FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
  79. UTF8Encoding encoding = new UTF8Encoding();
  80. FileWriter.Write(encoding.GetBytes("192.168.50.211"), 0, encoding.GetByteCount("192.168.50.211"));
  81. FileWriter.Close();
  82. Application.Quit();
  83. }
  84. }
  85. //建立链接
  86. private void ClickConnect()
  87. {
  88. Debug.Log("ClickConnect");
  89. isConnect = true;
  90. try
  91. {
  92. int _port = Convert.ToInt32(inputPort); //获取端口号
  93. string _ip = inputIp; //获取ip地址
  94. Debug.Log("ClickConnect1 "+ _ip+ _port);
  95. //创建客户端Socket,获得远程ip和端口号
  96. socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  97. IPAddress ip = IPAddress.Parse(_ip);
  98. IPEndPoint point = new IPEndPoint(ip, _port);
  99. Debug.Log("ClickConnect2");
  100. socketSend.Connect(point);
  101. Debug.Log("连接成功 , " + " ip = " + ip + " port = " + _port);
  102. staInfo = ip + ":" + _port + " 连接成功";
  103. Thread r_thread = new Thread(Received); //开启新的线程,不停的接收服务器发来的消息
  104. r_thread.IsBackground = true;
  105. r_thread.Start();
  106. Thread s_thread = new Thread(SendMessage); //开启新的线程,不停的给服务器发送消息
  107. s_thread.IsBackground = true;
  108. s_thread.Start();
  109. }
  110. catch (Exception e)
  111. {
  112. Debug.LogError(e.ToString());
  113. Debug.Log("IP或者端口号错误......");
  114. staInfo = "IP或者端口号错误......";
  115. isConnect = false;
  116. }
  117. }
  118. /// <summary>
  119. /// 接收服务端返回的消息
  120. /// </summary>
  121. void Received()
  122. {
  123. while (true)
  124. {
  125. try
  126. {
  127. byte[] buffer = new byte[1024 * 6];
  128. //实际接收到的有效字节数
  129. int len = socketSend.Receive(buffer);
  130. if (len == 0)
  131. {
  132. // isConnect = false;
  133. break;
  134. }
  135. recMes = Encoding.UTF8.GetString(buffer, 0, len);
  136. Debug.Log("客户端接收到的数据 : " + recMes);
  137. recTimes++;
  138. staInfo = "接收到一次数据,接收次数为 :" + recTimes;
  139. // Debug.Log("接收次数为:" + recTimes);
  140. queueRecMsg.Enqueue(recMes);
  141. }
  142. catch { }
  143. }
  144. }
  145. public void SendData()
  146. {
  147. Debug.Log("sendData");
  148. if (socketSend!=null&&SocketExtensions.IsConnected(socketSend))
  149. {
  150. if(NetWorkLANManager.Instance.createDesMsg.Count>0)
  151. {
  152. Message = NetWorkLANManager.Instance.createDesMsg.Dequeue();
  153. clickSend = true;
  154. return;
  155. }
  156. if(NetWorkLANManager.Instance.queueMsg.Count>0)
  157. {
  158. Message = NetWorkLANManager.Instance.queueMsg.Dequeue();
  159. clickSend = true;
  160. }
  161. }
  162. }
  163. /// <summary>
  164. /// 向服务器发送消息
  165. /// </summary>
  166. /// <param name="sender"></param>
  167. /// <param name="e"></param>
  168. void SendMessage()
  169. {
  170. try
  171. {
  172. while (true)
  173. {
  174. if (clickSend) //如果点击了发送按钮
  175. {
  176. clickSend = false;
  177. if (socketSend.Connected)
  178. {
  179. byte[] buffer = new byte[1024 * 6];
  180. buffer = Encoding.UTF8.GetBytes(Message);
  181. socketSend.Send(buffer);
  182. // Debug.Log("发送的数据为:" + Message);
  183. }
  184. else
  185. {
  186. isConnect = false;
  187. }
  188. }
  189. }
  190. }
  191. catch { }
  192. }
  193. private void OnDisable()
  194. {
  195. Debug.Log("begin OnDisable()");
  196. if (socketSend.Connected)
  197. {
  198. try
  199. {
  200. socketSend.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  201. socketSend.Close(); //关闭Socket连接并释放所有相关资源
  202. }
  203. catch (Exception e)
  204. {
  205. print(e.Message);
  206. }
  207. }
  208. Debug.Log("end OnDisable()");
  209. }
  210. //用户界面
  211. //void OnGUI()
  212. //{
  213. // //GUI.color = Color.black;
  214. // //GUI.Label(new Rect(65, 10, 60, 20), "状态信息");
  215. // //GUI.Label(new Rect(135, 10, 80, 60), staInfo);
  216. // //GUI.Label(new Rect(65, 70, 50, 20), "服务器ip地址");
  217. // //inputIp = GUI.TextField(new Rect(125, 70, 100, 20), inputIp, 20);
  218. // //GUI.Label(new Rect(65, 110, 50, 20), "服务器端口");
  219. // //inputPort = GUI.TextField(new Rect(125, 110, 100, 20), inputPort, 20);
  220. // //GUI.Label(new Rect(65, 150, 80, 20), "接收到消息:");
  221. // //GUI.Label(new Rect(155, 150, 80, 20), recMes);
  222. // //GUI.Label(new Rect(65, 190, 80, 20), "发送的消息:");
  223. // //Message = GUI.TextField(new Rect(155, 190, 100, 20), Message, 20);
  224. // //if (GUI.Button(new Rect(65, 270, 300, 100), "发送信息"))
  225. // //{
  226. // // clickSend = true;
  227. // //}
  228. //}
  229. }