TClient.cs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. using UnityEngine;
  2. using System.Collections;
  3. //引入库
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Collections.Generic;
  9. using LitJson;
  10. public class TClient : MonoBehaviour
  11. {
  12. string editString = "hello wolrd"; //编辑框文字
  13. public delegate void OnMessagedDelegate(string data);
  14. public OnMessagedDelegate OnMessaged;
  15. Socket serverSocket; //服务器端socket
  16. IPAddress ip; //主机ip
  17. IPEndPoint ipEnd;
  18. string recvStr; //接收的字符串
  19. string sendStr; //发送的字符串
  20. byte[] recvData = new byte[1024]; //接收的数据,必须为字节
  21. byte[] sendData = new byte[1024]; //发送的数据,必须为字节
  22. int recvLen; //接收的数据长度
  23. Thread connectThread; //连接线程
  24. public static TClient Instance;
  25. public bool isClient=false;
  26. //初始化
  27. public void InitSocket(string text = "127.0.0.1")
  28. {
  29. if(isClient)
  30. {
  31. SocketQuit();
  32. }
  33. isClient = true;
  34. Debug.Log(text);
  35. //定义服务器的IP和端口,端口与服务器对应
  36. ip = IPAddress.Parse(text); //可以是局域网或互联网ip,此处是本机
  37. ipEnd = new IPEndPoint(ip, 50001);
  38. //开启一个线程连接,必须的,否则主线程卡死
  39. connectThread = new Thread(new ThreadStart(SocketReceive));
  40. connectThread.Start();
  41. }
  42. Queue<string> queue =new Queue<string>();
  43. public void SocketConnet()
  44. {
  45. if (serverSocket != null)
  46. serverSocket.Close();
  47. //定义套接字类型,必须在子线程中定义
  48. serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  49. //连接
  50. serverSocket.Connect(ipEnd);
  51. //输出初次连接收到的字符串
  52. // recvLen = serverSocket.Receive(recvData);
  53. // recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
  54. // print(recvStr);
  55. // if(queue!=null)
  56. // {
  57. // queue.Enqueue(recvStr);
  58. // }
  59. }
  60. public static byte[] int2Bytes(int i)
  61. {
  62. byte[] b = new byte[4];
  63. b[0] = (byte)i; //将int类型的最后8位赋值给0号位。强转是将高位去掉
  64. b[1] = (byte)(i >> 8);
  65. b[2] = (byte)(i >> 16);
  66. b[3] = (byte)(i >> 24);
  67. return b;
  68. }
  69. public void SocketSend(string sendStr)
  70. {
  71. //清空发送缓存
  72. sendData = new byte[1024];
  73. //数据类型转换
  74. sendData = Encoding.ASCII.GetBytes(sendStr);
  75. byte[] bb = int2Bytes(sendData.Length);
  76. serverSocket.Send(bb, bb.Length, SocketFlags.None);
  77. //发送
  78. serverSocket.Send(sendData, sendData.Length, SocketFlags.None);
  79. }
  80. void SocketReceive()
  81. {
  82. SocketConnet();
  83. //不断接收服务器发来的数据
  84. while (true)
  85. {
  86. byte[] recvBytes = new byte[4];
  87. int bodyLength = serverSocket.Receive(recvBytes, 0, recvBytes.Length, SocketFlags.None);
  88. int baotou = TServerC.bytes2Int(recvBytes);
  89. //对data清零
  90. recvData = new byte[baotou];
  91. //获取收到的数据的长度
  92. recvLen = 0;
  93. while (recvLen != recvData.Length)
  94. {
  95. // Debug.Log("准备接收==>" + recvLen);
  96. recvLen += serverSocket.Receive(recvData, recvLen, recvData.Length - recvLen, SocketFlags.None);
  97. // Debug.Log("server 接收到Client 长度==>" + recvLen);
  98. }
  99. if (recvLen == 0)
  100. {
  101. SocketQuit();
  102. continue;
  103. }
  104. recvStr = Encoding.ASCII.GetString(recvData, 0, recvLen);
  105. queue.Enqueue(recvStr);
  106. }
  107. }
  108. public void SocketQuit()
  109. {
  110. //关闭线程
  111. if (connectThread != null)
  112. {
  113. connectThread.Interrupt();
  114. connectThread.Abort();
  115. }
  116. //最后关闭服务器
  117. if (serverSocket != null)
  118. serverSocket.Close();
  119. isClient = false;
  120. }
  121. // Use this for initialization
  122. void Start()
  123. {
  124. Instance = this;
  125. //InitSocket();
  126. }
  127. void OnGUI()
  128. {
  129. // editString = GUI.TextField(new Rect(10, 10, 100, 20), editString);
  130. // if (GUI.Button(new Rect(10, 30, 60, 20), "send"))
  131. // SocketSend(editString);
  132. }
  133. // Update is called once per frame
  134. void Update()
  135. {
  136. if (queue.Count>0)
  137. {
  138. string str = queue.Dequeue();
  139. Debug.Log("Str接收===:"+str);
  140. if (OnMessaged != null)
  141. {
  142. OnMessaged(str);
  143. }
  144. }
  145. // SocketSend("连接上了12312321321");
  146. }
  147. //程序退出则关闭连接
  148. void OnApplicationQuit()
  149. {
  150. SocketQuit();
  151. }
  152. }