client.cs 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. //Debug.Log("ipPath "+ ipPath);
  54. //var webRequest = UnityWebRequest.Get(ipPath);
  55. //yield return webRequest.SendWebRequest();
  56. //if (webRequest.error != null)
  57. //{
  58. // Debug.LogError(webRequest.error);
  59. //}
  60. //else
  61. //{
  62. // while (!webRequest.isDone)
  63. // {
  64. // yield return 0;
  65. // }
  66. // if (webRequest.isDone)
  67. // {
  68. // byte[] bytes = webRequest.downloadHandler.data;
  69. // Debug.Log(" DownLoad OK " + ipPath);
  70. // Debug.Log(webRequest.downloadHandler.data.Length);
  71. // // if (!File.Exists(Application.dataPath + "/Resources/YourVideoName.mp4"))
  72. // inputIp = System.Text.Encoding.Default.GetString(webRequest.downloadHandler.data);
  73. // Debug.Log(inputIp);
  74. // ClickConnect();
  75. // }
  76. //}
  77. FileStream fileStream = new FileStream(ipPath, FileMode.Open, FileAccess.Read);
  78. fileStream.Seek(0, SeekOrigin.Begin);
  79. //创建文件长度缓冲区
  80. byte[] bytes = new byte[fileStream.Length];
  81. //读取文件
  82. fileStream.Read(bytes, 0, (int)fileStream.Length);
  83. Debug.Log(" bytes " + bytes.Length);
  84. //释放文件读取流
  85. fileStream.Close();
  86. fileStream.Dispose();
  87. fileStream = null;
  88. inputIp = System.Text.Encoding.Default.GetString(bytes);
  89. Debug.Log(inputIp);
  90. ClickConnect();
  91. }
  92. else
  93. {
  94. Directory.CreateDirectory(Application.persistentDataPath + "/Ipconfig");
  95. FileInfo fileInfo = new FileInfo(ipPath);
  96. //设置Log文件输出地址
  97. FileStream FileWriter = fileInfo.Open(FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
  98. UTF8Encoding encoding = new UTF8Encoding();
  99. FileWriter.Write(encoding.GetBytes("192.168.50.17"), 0, encoding.GetByteCount("192.168.50.17"));
  100. FileWriter.Close();
  101. Application.Quit();
  102. }
  103. }
  104. //建立链接
  105. private void ClickConnect()
  106. {
  107. Debug.Log("ClickConnect");
  108. isConnect = true;
  109. try
  110. {
  111. int _port = Convert.ToInt32(inputPort); //获取端口号
  112. string _ip = inputIp; //获取ip地址
  113. Debug.Log("ClickConnect1 "+ _ip+ _port);
  114. if (inputIp == null)
  115. return;
  116. //创建客户端Socket,获得远程ip和端口号
  117. socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  118. IPAddress ip = IPAddress.Parse(_ip);
  119. IPEndPoint point = new IPEndPoint(ip, _port);
  120. Debug.Log("ClickConnect2");
  121. socketSend.Connect(point);
  122. Debug.Log("连接成功 , " + " ip = " + ip + " port = " + _port);
  123. staInfo = ip + ":" + _port + " 连接成功";
  124. Thread r_thread = new Thread(Received); //开启新的线程,不停的接收服务器发来的消息
  125. r_thread.IsBackground = true;
  126. r_thread.Start();
  127. Thread s_thread = new Thread(SendMessage); //开启新的线程,不停的给服务器发送消息
  128. s_thread.IsBackground = true;
  129. s_thread.Start();
  130. }
  131. catch (Exception e)
  132. {
  133. Debug.LogError(e.ToString());
  134. Debug.Log("IP或者端口号错误......");
  135. staInfo = "IP或者端口号错误......";
  136. isConnect = false;
  137. }
  138. }
  139. /// <summary>
  140. /// 接收服务端返回的消息
  141. /// </summary>
  142. void Received()
  143. {
  144. while (true)
  145. {
  146. try
  147. {
  148. byte[] buffer = new byte[1024 * 6];
  149. //实际接收到的有效字节数
  150. int len = socketSend.Receive(buffer);
  151. if (len == 0)
  152. {
  153. // isConnect = false;
  154. break;
  155. }
  156. recMes = Encoding.UTF8.GetString(buffer, 0, len);
  157. Debug.Log("客户端接收到的数据 : " + recMes);
  158. recTimes++;
  159. staInfo = "接收到一次数据,接收次数为 :" + recTimes;
  160. // Debug.Log("接收次数为:" + recTimes);
  161. queueRecMsg.Enqueue(recMes);
  162. }
  163. catch { }
  164. }
  165. }
  166. public void SendData()
  167. {
  168. Debug.Log("sendData");
  169. if (socketSend!=null&&SocketExtensions.IsConnected(socketSend))
  170. {
  171. if(NetWorkLANManager.Instance.createDesMsg.Count>0)
  172. {
  173. Message = NetWorkLANManager.Instance.createDesMsg.Dequeue();
  174. clickSend = true;
  175. return;
  176. }
  177. if(NetWorkLANManager.Instance.queueMsg.Count>0)
  178. {
  179. Message = NetWorkLANManager.Instance.queueMsg.Dequeue();
  180. clickSend = true;
  181. }
  182. }
  183. }
  184. /// <summary>
  185. /// 向服务器发送消息
  186. /// </summary>
  187. /// <param name="sender"></param>
  188. /// <param name="e"></param>
  189. void SendMessage()
  190. {
  191. try
  192. {
  193. while (true)
  194. {
  195. if (clickSend) //如果点击了发送按钮
  196. {
  197. clickSend = false;
  198. if (socketSend.Connected)
  199. {
  200. byte[] buffer = new byte[1024 * 6];
  201. buffer = Encoding.UTF8.GetBytes(Message);
  202. socketSend.Send(buffer);
  203. // Debug.Log("发送的数据为:" + Message);
  204. }
  205. else
  206. {
  207. isConnect = false;
  208. }
  209. }
  210. }
  211. }
  212. catch { }
  213. }
  214. private void OnDisable()
  215. {
  216. Debug.Log("begin OnDisable()");
  217. if (socketSend.Connected)
  218. {
  219. try
  220. {
  221. socketSend.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  222. socketSend.Close(); //关闭Socket连接并释放所有相关资源
  223. }
  224. catch (Exception e)
  225. {
  226. print(e.Message);
  227. }
  228. }
  229. Debug.Log("end OnDisable()");
  230. }
  231. //用户界面
  232. //void OnGUI()
  233. //{
  234. // //GUI.color = Color.black;
  235. // //GUI.Label(new Rect(65, 10, 60, 20), "状态信息");
  236. // //GUI.Label(new Rect(135, 10, 80, 60), staInfo);
  237. // //GUI.Label(new Rect(65, 70, 50, 20), "服务器ip地址");
  238. // //inputIp = GUI.TextField(new Rect(125, 70, 100, 20), inputIp, 20);
  239. // //GUI.Label(new Rect(65, 110, 50, 20), "服务器端口");
  240. // //inputPort = GUI.TextField(new Rect(125, 110, 100, 20), inputPort, 20);
  241. // //GUI.Label(new Rect(65, 150, 80, 20), "接收到消息:");
  242. // //GUI.Label(new Rect(155, 150, 80, 20), recMes);
  243. // //GUI.Label(new Rect(65, 190, 80, 20), "发送的消息:");
  244. // //Message = GUI.TextField(new Rect(155, 190, 100, 20), Message, 20);
  245. // //if (GUI.Button(new Rect(65, 270, 300, 100), "发送信息"))
  246. // //{
  247. // // clickSend = true;
  248. // //}
  249. //}
  250. }