server.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Net.Sockets; //调用socket
  6. using System.Text;
  7. using System.Threading; //调用线程
  8. using UnityEngine;
  9. using System.IO;
  10. using System.Net.NetworkInformation;
  11. using BeinLab.Util;
  12. public class server : MonoBehaviour
  13. {
  14. //定义变量(与GUI一致)
  15. private string info = "NULL"; //状态信息
  16. private string recMes = "NULL"; //接收到的信息
  17. private int recTimes = 0; //接收到的信息次数
  18. private string inputIp = "192.168.50.17"; //ip地址(本地)
  19. private string inputPort = "18180"; //端口值
  20. private string Message = "NULL"; //用以发送的信息
  21. private Socket socketWatch; //用以监听的套接字
  22. private Socket socketSend; //用以和客户端通信的套接字
  23. private bool isSendData = false; //是否点击发送数据按钮
  24. private bool clickConnectBtn = false; //是否点击监听按钮
  25. public Queue<String> queueRecMsg;
  26. // Start is called before the first frame update
  27. void Start()
  28. {
  29. inputIp = GetIP();
  30. ClickConnect();
  31. TimerMgr.Instance.CreateTimer(() => { SendData(); }, 0.1f, -1);
  32. queueRecMsg = new Queue<string>();
  33. // Debug.Log(GetIP());
  34. }
  35. // Update is called once per frame
  36. void Update()
  37. {
  38. }
  39. /// <summary>
  40. /// 获取本机IP
  41. /// </summary>
  42. /// <param name="Addfam">要获取的IP类型</param>
  43. /// <returns></returns>
  44. public string GetIP()
  45. {
  46. string output = "";
  47. IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName()); //Dns.GetHostName()获取本机名Dns.GetHostAddresses()根据本机名获取ip地址组
  48. foreach (IPAddress ip in ips)
  49. {
  50. if (ip.AddressFamily == AddressFamily.InterNetwork)
  51. {
  52. Debug.Log( ip.ToString()); //ipv4
  53. output = ip.ToString();
  54. }
  55. else if (ip.AddressFamily == AddressFamily.InterNetworkV6)
  56. {
  57. Debug.Log(ip.ToString()); //ipv6
  58. output = ip.ToString();
  59. }
  60. }
  61. return output;
  62. }
  63. //建立tcp通信链接
  64. private void ClickConnect()
  65. {
  66. try
  67. {
  68. int _port = Convert.ToInt32(inputPort); //获取端口号(32位,4个字节)
  69. string _ip = inputIp; //获取ip地址
  70. Debug.Log(" ip 地址是 :" + _ip);
  71. Debug.Log(" 端口号是 :" + _port);
  72. clickConnectBtn = true; //点击了监听按钮,更改状态
  73. info = "ip地址是 : " + _ip + "端口号是 : " + _port;
  74. //点击开始监听时 在服务端创建一个负责监听IP和端口号的Socket
  75. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  76. IPAddress ip = IPAddress.Parse(inputIp);
  77. IPEndPoint point = new IPEndPoint(ip, _port); //创建对象端口
  78. socketWatch.Bind(point); //绑定端口号
  79. Debug.Log("监听成功!");
  80. info = "监听成功";
  81. socketWatch.Listen(10); //设置监听,最大同时连接10台
  82. //创建监听线程
  83. Thread thread = new Thread(Listen);
  84. thread.IsBackground = true;
  85. thread.Start(socketWatch);
  86. }
  87. catch { }
  88. }
  89. /// <summary>
  90. /// 等待客户端的连接 并且创建与之通信的Socket
  91. /// </summary>
  92. void Listen(object o)
  93. {
  94. try
  95. {
  96. Socket socketWatch = o as Socket;
  97. while (true)
  98. {
  99. socketSend = socketWatch.Accept(); //等待接收客户端连接
  100. Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
  101. info = socketSend.RemoteEndPoint.ToString() + " 连接成功!";
  102. Thread r_thread = new Thread(Received); //开启一个新线程,执行接收消息方法
  103. r_thread.IsBackground = true;
  104. r_thread.Start(socketSend);
  105. Thread s_thread = new Thread(SendMessage); //开启一个新线程,执行发送消息方法
  106. s_thread.IsBackground = true;
  107. s_thread.Start(socketSend);
  108. }
  109. }
  110. catch { }
  111. }
  112. // 服务器端不停的接收客户端发来的消息
  113. void Received(object o)
  114. {
  115. try
  116. {
  117. Socket socketSend = o as Socket;
  118. while (true)
  119. {
  120. byte[] buffer = new byte[1024 * 6]; //客户端连接服务器成功后,服务器接收客户端发送的消息
  121. int len = socketSend.Receive(buffer); //实际接收到的有效字节数
  122. if (len == 0)
  123. {
  124. break;
  125. }
  126. string str = Encoding.UTF8.GetString(buffer, 0, len);
  127. Debug.Log("接收到的消息:" + socketSend.RemoteEndPoint + ":" + str);
  128. recMes = str;
  129. recTimes++;
  130. info = "接收到一次数据,接收次数为:" + recTimes;
  131. // Debug.Log("接收数据次数:" + recTimes);
  132. queueRecMsg.Enqueue(recMes);
  133. }
  134. }
  135. catch { }
  136. }
  137. public void SendData()
  138. {
  139. if (socketSend != null)
  140. Debug.Log("sendData " + SocketExtensions.IsConnected(socketSend));
  141. if (socketSend!=null&& SocketExtensions.IsConnected(socketSend))
  142. {
  143. if(NetWorkLANManager.Instance.createDesMsg.Count>0)
  144. {
  145. Message = NetWorkLANManager.Instance.createDesMsg.Dequeue();
  146. isSendData = true;
  147. return;
  148. }
  149. else if (NetWorkLANManager.Instance.queueMsg.Count > 0)
  150. {
  151. Message = NetWorkLANManager.Instance.queueMsg.Dequeue();
  152. isSendData = true;
  153. }
  154. }
  155. }
  156. // 服务器端不停的向客户端发送消息
  157. void SendMessage(object o)
  158. {
  159. try
  160. {
  161. Socket socketSend = o as Socket;
  162. while (true)
  163. {
  164. if (isSendData)
  165. {
  166. isSendData = false;
  167. byte[] sendByte = Encoding.UTF8.GetBytes(Message);
  168. Debug.Log("发送的数据为 :" + Message);
  169. Debug.Log("发送的数据字节长度 :" + sendByte.Length);
  170. socketSend.Send(sendByte);
  171. }
  172. }
  173. }
  174. catch { }
  175. }
  176. // 关闭连接,释放资源
  177. private void OnDisable()
  178. {
  179. Debug.Log("begin OnDisable()");
  180. if (clickConnectBtn)
  181. {
  182. try
  183. {
  184. socketWatch.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  185. socketWatch.Close(); //关闭Socket连接并释放所有相关资源
  186. socketSend.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  187. socketSend.Close(); //关闭Socket连接并释放所有相关资源
  188. }
  189. catch (Exception e)
  190. {
  191. Debug.Log(e.Message);
  192. }
  193. }
  194. Debug.Log("end OnDisable()");
  195. }
  196. //交互界面(代码创建)
  197. void OnGUI()
  198. {
  199. GUI.color = Color.black; //字体颜色
  200. GUI.Label(new Rect(65, 10, 80, 20), "状态信息");
  201. GUI.Label(new Rect(155, 10, 80, 70), info);
  202. GUI.Label(new Rect(65, 80, 80, 20), "接收到消息:");
  203. GUI.Label(new Rect(155, 80, 80, 20), recMes);
  204. GUI.Label(new Rect(65, 120, 80, 20), "发送的消息:");
  205. Message = GUI.TextField(new Rect(155, 120, 100, 20), Message, 20);
  206. GUI.Label(new Rect(65, 160, 80, 20), "本机ip地址:");
  207. inputIp = GUI.TextField(new Rect(155, 160, 100, 20), inputIp, 20);
  208. GUI.Label(new Rect(65, 200, 80, 20), "本机端口号:");
  209. inputPort = GUI.TextField(new Rect(155, 200, 100, 20), inputPort, 20);
  210. if (GUI.Button(new Rect(65, 240, 60, 20), "开始监听"))
  211. {
  212. ClickConnect(); //点击开始
  213. }
  214. if (GUI.Button(new Rect(65, 280, 60, 20), "发送数据"))
  215. {
  216. isSendData = true; //发送数据
  217. }
  218. }
  219. }