Test de communication de paquets entre un client et un serveur
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System;
  7. public class Client : MonoBehaviour
  8. {
  9. public static Client instance;
  10. public static int dataBufferSize = 4096;
  11. public string ip = "127.0.0.1";
  12. public int port = 26950;
  13. public int myId = 0;
  14. public TCP tcp;
  15. public UDP udp;
  16. private bool isConnected = false;
  17. private delegate void PacketHandler(Packet _packet);
  18. private static Dictionary<int, PacketHandler> packetHandlers;
  19. private void Awake()
  20. {
  21. if (instance == null)
  22. {
  23. instance = this;
  24. }
  25. else if (instance != this)
  26. {
  27. Debug.Log("Instance already exists. Destroying object !");
  28. Destroy(this);
  29. }
  30. }
  31. private void Start()
  32. {
  33. tcp = new TCP();
  34. udp = new UDP();
  35. }
  36. private void OnApplicationQuit()
  37. {
  38. Disconnect();
  39. }
  40. public void ConnectToServer()
  41. {
  42. InitializeClientData();
  43. isConnected = true;
  44. tcp.Connect();
  45. }
  46. public class TCP
  47. {
  48. public TcpClient socket;
  49. private NetworkStream stream;
  50. private Packet receivedData;
  51. private byte[] receiveBuffer;
  52. public void Connect()
  53. {
  54. socket = new TcpClient
  55. {
  56. ReceiveBufferSize = dataBufferSize,
  57. SendBufferSize = dataBufferSize
  58. };
  59. receiveBuffer = new byte[dataBufferSize];
  60. socket.BeginConnect(instance.ip, instance.port, ConnectCallback, socket);
  61. }
  62. private void ConnectCallback(IAsyncResult _result)
  63. {
  64. socket.EndConnect(_result);
  65. Debug.Log("test");
  66. if (!socket.Connected)
  67. {
  68. Debug.Log("Couldn't connect");
  69. return;
  70. }
  71. stream = socket.GetStream();
  72. receivedData = new Packet();
  73. stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
  74. }
  75. public void SendData(Packet _packet)
  76. {
  77. try
  78. {
  79. if (socket != null)
  80. {
  81. stream.BeginWrite(_packet.ToArray(), 0, _packet.Length(), null, null);
  82. }
  83. }
  84. catch (Exception _ex)
  85. {
  86. Debug.Log($"Error sending data to server via TCP : {_ex}");
  87. }
  88. }
  89. private void ReceiveCallback(IAsyncResult _result)
  90. {
  91. try
  92. {
  93. int _byteLength = stream.EndRead(_result);
  94. if (_byteLength <= 0)
  95. {
  96. instance.Disconnect();
  97. return;
  98. }
  99. byte[] _data = new byte[_byteLength];
  100. Array.Copy(receiveBuffer, _data, _byteLength);
  101. receivedData.Reset(HandleData(_data));
  102. stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
  103. }
  104. catch (Exception)
  105. {
  106. Disconnect();
  107. }
  108. }
  109. private bool HandleData(byte[] _data)
  110. {
  111. int _packetLength = 0;
  112. receivedData.SetBytes(_data);
  113. if (receivedData.UnreadLength() >= 4)
  114. {
  115. _packetLength = receivedData.ReadInt();
  116. if (_packetLength <= 0)
  117. {
  118. return true;
  119. }
  120. }
  121. while (_packetLength > 0 && _packetLength <= receivedData.UnreadLength())
  122. {
  123. byte[] _packetBytes = receivedData.ReadBytes(_packetLength);
  124. ThreadManager.ExecuteOnMainThread(() =>
  125. {
  126. using (Packet _packet = new Packet(_packetBytes))
  127. {
  128. int _packetId = _packet.ReadInt();
  129. packetHandlers[_packetId](_packet);
  130. }
  131. });
  132. _packetLength = 0;
  133. if (receivedData.UnreadLength() >= 4)
  134. {
  135. _packetLength = receivedData.ReadInt();
  136. if (_packetLength <= 0)
  137. {
  138. return true;
  139. }
  140. }
  141. }
  142. if (_packetLength <= 1)
  143. {
  144. return true;
  145. }
  146. return false;
  147. }
  148. private void Disconnect()
  149. {
  150. instance.Disconnect();
  151. stream = null;
  152. receivedData = null;
  153. receiveBuffer = null;
  154. socket = null;
  155. }
  156. }
  157. public class UDP
  158. {
  159. public UdpClient socket;
  160. public IPEndPoint endPoint;
  161. public void Connect(int _localPort)
  162. {
  163. socket = new UdpClient(_localPort);
  164. endPoint = new IPEndPoint(IPAddress.Parse(instance.ip), instance.port);
  165. socket.Connect(endPoint);
  166. socket.BeginReceive(ReceiveCallback, null);
  167. using (Packet _packet = new Packet())
  168. {
  169. SendData(_packet);
  170. }
  171. }
  172. public void SendData(Packet _packet)
  173. {
  174. try
  175. {
  176. _packet.InsertInt(instance.myId);
  177. if (socket != null)
  178. {
  179. socket.BeginSend(_packet.ToArray(), _packet.Length(), null, null);
  180. }
  181. }
  182. catch (Exception _ex)
  183. {
  184. Debug.Log($"Error sending data to server via UDP : {_ex}");
  185. }
  186. }
  187. private void ReceiveCallback(IAsyncResult _result)
  188. {
  189. try
  190. {
  191. byte[] _data = socket.EndReceive(_result, ref endPoint);
  192. socket.BeginReceive(ReceiveCallback, null);
  193. if (_data.Length < 4)
  194. {
  195. instance.Disconnect();
  196. return;
  197. }
  198. HandleData(_data);
  199. }
  200. catch (Exception)
  201. {
  202. Disconnect();
  203. }
  204. }
  205. private void HandleData(byte[] _data)
  206. {
  207. using (Packet _packet = new Packet(_data))
  208. {
  209. int _packetLength = _packet.ReadInt();
  210. _data = _packet.ReadBytes(_packetLength);
  211. }
  212. ThreadManager.ExecuteOnMainThread(() =>
  213. {
  214. using (Packet _packet = new Packet(_data))
  215. {
  216. int _packetId = _packet.ReadInt();
  217. packetHandlers[_packetId](_packet);
  218. }
  219. });
  220. }
  221. private void Disconnect()
  222. {
  223. instance.Disconnect();
  224. endPoint = null;
  225. socket = null;
  226. }
  227. }
  228. private void InitializeClientData()
  229. {
  230. packetHandlers = new Dictionary<int, PacketHandler>()
  231. {
  232. { (int)ServerPackets.welcome, ClientHandle.Welcome },
  233. { (int)ServerPackets.spawnPlayer, ClientHandle.SpawnPlayer },
  234. { (int)ServerPackets.playerPosition, ClientHandle.PlayerPosition },
  235. { (int)ServerPackets.playerRotation, ClientHandle.PlayerRotation },
  236. { (int)ServerPackets.playerDisconnected, ClientHandle.PlayerDisconnected },
  237. { (int)ServerPackets.playerHealth, ClientHandle.PlayerHealth },
  238. { (int)ServerPackets.playerRespawned, ClientHandle.PlayerRespawned }
  239. };
  240. Debug.Log("Initialized packets.");
  241. }
  242. private void Disconnect()
  243. {
  244. if (isConnected)
  245. {
  246. isConnected = false;
  247. tcp.socket.Close();
  248. udp.socket.Close();
  249. Debug.Log("Disconnected from server");
  250. }
  251. }
  252. }