server.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 LitJson;
  12. //
  13. public class server : MonoBehaviour
  14. {
  15. //定义变量(与GUI一致)
  16. private string info = "NULL"; //状态信息
  17. private string recMes = "NULL"; //接收到的信息
  18. private int recTimes = 0; //接收到的信息次数
  19. private string inputIp = "192.168.50.17"; //ip地址(本地)
  20. private string inputPort = "8089"; //端口值
  21. private string Message = "NULL"; //用以发送的信息
  22. private Socket socketWatch;
  23. private static Socket socketWatchudp; //用以监听的套接字
  24. public static Socket socketSend; //用以和客户端通信的套接字
  25. private bool isSendData = false; //是否点击发送数据按钮
  26. private bool clickConnectBtn = false; //是否点击监听按钮
  27. public Queue<String> queueRecMsg;
  28. // Start is called before the first frame update
  29. void Start()
  30. {
  31. inputIp = GetIP();
  32. ClickConnect();
  33. // TimerMgr.Instance.CreateTimer(() => { SendData(); }, 0.1f, -1);
  34. queueRecMsg = new Queue<string>();
  35. // Debug.Log(GetIP());
  36. }
  37. // Update is called once per frame
  38. void Update()
  39. {
  40. }
  41. /// <summary>
  42. /// 获取本机IP
  43. /// </summary>
  44. /// <param name="Addfam">要获取的IP类型</param>
  45. /// <returns></returns>
  46. public string GetIP()
  47. {
  48. return GetLocalIPAddress();
  49. }
  50. //建立tcp通信链接
  51. private void ClickConnect()
  52. {
  53. int _port = Convert.ToInt32(inputPort); //获取端口号(32位,4个字节)
  54. string _ip = GetLocalIPAddress(); //获取ip地址
  55. Debug.Log(" ip 地址是 :" + _ip);
  56. Debug.Log(" 端口号是 :" + _port);
  57. clickConnectBtn = true; //点击了监听按钮,更改状态
  58. info = "ip地址是 : " + _ip + "端口号是 : " + _port;
  59. //点击开始监听时 在服务端创建一个负责监听IP和端口号的Socket
  60. socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  61. IPAddress ip = IPAddress.Parse(inputIp);
  62. IPEndPoint point = new IPEndPoint(ip, _port); //创建对象端口
  63. socketWatch.Bind(point); //绑定端口号
  64. Debug.Log("TCP监听成功!");
  65. info = "监听成功";
  66. socketWatch.Listen(10); //设置监听,最大同时连接10台
  67. //创建监听线程
  68. Thread thread = new Thread(Listen);
  69. thread.IsBackground = true;
  70. thread.Start(socketWatch);
  71. }
  72. static IPEndPoint broadcastEndPoint;
  73. void ReceiveMsg()
  74. {
  75. byte[] data = new byte[1024];
  76. EndPoint point = new IPEndPoint(IPAddress.Any, 0);
  77. while (true)
  78. {
  79. int length = socketWatchudp.ReceiveFrom(data, ref point);
  80. string mes = Encoding.UTF8.GetString(data, 0, length);
  81. Debug.Log("服务器从" + ((IPEndPoint)point).Address + "端口:" + ((IPEndPoint)point).Port + "收到了消息:" + mes);
  82. }
  83. }
  84. string GetLocalIPAddress()
  85. {
  86. var host = Dns.GetHostEntry(Dns.GetHostName());
  87. foreach (var ip in host.AddressList)
  88. {
  89. if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  90. {
  91. return ip.ToString();
  92. }
  93. }
  94. throw new System.Exception("No network adapters with an IPv4 address in the system!");
  95. }
  96. static List<Socket> sockets = new List<Socket>();
  97. /// <summary>
  98. /// 等待客户端的连接 并且创建与之通信的Socket
  99. /// </summary>
  100. void Listen(object o)
  101. {
  102. try
  103. {
  104. Socket socketWatch = o as Socket;
  105. while (true)
  106. {
  107. socketSend = socketWatch.Accept(); //等待接收客户端连接
  108. sockets.Add(socketSend);
  109. Debug.Log(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
  110. info = socketSend.RemoteEndPoint.ToString() + " 连接成功!";
  111. Thread r_thread = new Thread(Received); //开启一个新线程,执行接收消息方法
  112. r_thread.IsBackground = true;
  113. r_thread.Start(socketSend);
  114. // Thread s_thread = new Thread(SendMessage); //开启一个新线程,执行发送消息方法
  115. // s_thread.IsBackground = true;
  116. // s_thread.Start(socketSend);
  117. }
  118. }
  119. catch { }
  120. }
  121. // 服务器端不停的接收客户端发来的消息
  122. void Received(object o)
  123. {
  124. try
  125. {
  126. Socket socketSend = o as Socket;
  127. while (true)
  128. {
  129. byte[] buffer = new byte[1024 * 6]; //客户端连接服务器成功后,服务器接收客户端发送的消息
  130. int len = socketSend.Receive(buffer); //实际接收到的有效字节数
  131. if (len == 0)
  132. {
  133. Debug.Log("断开 " );
  134. break;
  135. }
  136. string recvStr = Encoding.UTF8.GetString(buffer, 0, len);
  137. Debug.Log("收到信息 " + recvStr);
  138. try
  139. {
  140. string[] q1 = recvStr.Split(new char[2] { 'R', 'T' });
  141. double q = double.Parse(q1[1]);
  142. string[] xRo = recvStr.Split(new char[2] { 'X', 'R' });
  143. string[] yRo = recvStr.Split(new char[2] { 'Y', 'X' });
  144. string[] zRo = recvStr.Split(new char[2] { 'Z', 'Y' });
  145. Debug.Log("收到x " + xRo[0]);
  146. #region 角度
  147. //float xro = -float.Parse(yRo[1]);
  148. //float yro = 180 - float.Parse(zRo[1]);
  149. //float zro = float.Parse(xRo[1]);
  150. float xro = -float.Parse(zRo[1]);
  151. float zro = -(180 - float.Parse(yRo[1]));
  152. float yro = float.Parse(xRo[1]);
  153. Vector3 jd = new Vector3(xro, 1.352f, zro);
  154. Quaternion q2 = Quaternion.Euler(jd);
  155. Debug.Log("角度为" + jd);
  156. #endregion
  157. #region 加速度
  158. //string[] xA = recvStr.Split(new char[2] { 'D', 'E' });
  159. //string[] yA = recvStr.Split(new char[2] { 'E', 'F' });
  160. //string[] zA = recvStr.Split(new char[2] { 'F', 'G' });
  161. //xa = float.Parse(xA[1]);
  162. //ya = float.Parse(yA[1]);
  163. //za = float.Parse(zA[1]);
  164. ////Debug.Log("加速度为" + xa+' '+ya+' '+za);
  165. //#endregion
  166. //#region 弯度
  167. //string[] wD= recvStr.Split(new char[2] { 'G', 'H' });
  168. //wd= int.Parse(wD[1]);
  169. #endregion
  170. //msgQueue.Enqueue(recvStr);
  171. //SZ90Y90X90R20T
  172. }
  173. catch
  174. {
  175. }
  176. }
  177. // Debug.Log("接收到的消息:" + socketSend.RemoteEndPoint + ":" + recvStr);
  178. // recMes = str;
  179. recTimes++;
  180. info = "接收到一次数据,接收次数为:" + recTimes;
  181. // Debug.Log("接收数据次数:" + recTimes);
  182. // queueRecMsg.Enqueue(recMes);
  183. // }
  184. }
  185. catch { }
  186. }
  187. public void SendData()
  188. {
  189. if (socketSend != null)
  190. Debug.Log("sendData " + SocketExtensions.IsConnected(socketSend));
  191. if (socketSend!=null&& SocketExtensions.IsConnected(socketSend))
  192. {
  193. if(NetWorkLANManager.Instance.createDesMsg.Count>0)
  194. {
  195. Message = NetWorkLANManager.Instance.createDesMsg.Dequeue();
  196. isSendData = true;
  197. return;
  198. }
  199. else if (NetWorkLANManager.Instance.queueMsg.Count > 0)
  200. {
  201. Message = NetWorkLANManager.Instance.queueMsg.Dequeue();
  202. isSendData = true;
  203. }
  204. }
  205. }
  206. // 服务器端不停的向客户端发送消息
  207. public static void SendMessage(JsonData data)
  208. {
  209. return;
  210. if (socketSend == null)
  211. {
  212. return;
  213. }
  214. for (int i = 0; i < sockets.Count; i++)
  215. {
  216. try
  217. {
  218. byte[] sendByte = Encoding.UTF8.GetBytes(data.ToJson());
  219. Debug.Log("发送的数据为 :" + data.ToJson());
  220. Debug.Log("发送的数据字节长度 :" + sendByte.Length);
  221. sockets[i].Send(sendByte);
  222. }
  223. catch { }
  224. }
  225. }
  226. // 关闭连接,释放资源
  227. private void OnDisable()
  228. {
  229. Debug.Log("begin OnDisable()");
  230. if (clickConnectBtn)
  231. {
  232. }
  233. Debug.Log("end OnDisable()");
  234. }
  235. private void OnDestroy()
  236. {
  237. socketWatch.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  238. socketWatch.Close();
  239. socketWatch.Dispose(); //关闭Socket连接并释放所有相关资源
  240. socketWatchudp.Shutdown(SocketShutdown.Both); //禁用Socket的发送和接收功能
  241. socketWatchudp.Close();
  242. socketWatchudp.Dispose();
  243. for (int i = 0; i < sockets.Count; i++)
  244. {
  245. sockets[i].Dispose();
  246. }
  247. }
  248. //交互界面(代码创建)
  249. void OnGUI()
  250. {
  251. /*
  252. GUI.color = Color.black; //字体颜色
  253. GUI.Label(new Rect(65, 10, 80, 20), "状态信息");
  254. GUI.Label(new Rect(155, 10, 80, 70), info);
  255. GUI.Label(new Rect(65, 80, 80, 20), "接收到消息:");
  256. GUI.Label(new Rect(155, 80, 80, 20), recMes);
  257. GUI.Label(new Rect(65, 120, 80, 20), "发送的消息:");
  258. Message = GUI.TextField(new Rect(155, 120, 100, 20), Message, 20);
  259. GUI.Label(new Rect(65, 160, 80, 20), "本机ip地址:");
  260. inputIp = GUI.TextField(new Rect(155, 160, 100, 20), inputIp, 20);
  261. GUI.Label(new Rect(65, 200, 80, 20), "本机端口号:");
  262. inputPort = GUI.TextField(new Rect(155, 200, 100, 20), inputPort, 20);
  263. if (GUI.Button(new Rect(65, 240, 60, 20), "开始监听"))
  264. {
  265. ClickConnect(); //点击开始
  266. }
  267. if (GUI.Button(new Rect(65, 280, 60, 20), "发送数据"))
  268. {
  269. isSendData = true; //发送数据
  270. }*/
  271. }
  272. }