client.cs 8.3 KB

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