NetSocket.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. #if DEBUG && !UNITY_WP_8_1 && !UNITY_WSA_8_1
  2. #if !WINRT || UNITY_EDITOR
  3. using System;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading;
  7. namespace FlyingWormConsole3.LiteNetLib
  8. {
  9. internal sealed class NetSocket
  10. {
  11. private Socket _udpSocketv4;
  12. private Socket _udpSocketv6;
  13. private NetEndPoint _localEndPoint;
  14. private Thread _threadv4;
  15. private Thread _threadv6;
  16. private bool _running;
  17. private readonly NetManager.OnMessageReceived _onMessageReceived;
  18. private static readonly IPAddress MulticastAddressV6 = IPAddress.Parse (NetConstants.MulticastGroupIPv6);
  19. private static readonly bool IPv6Support;
  20. private const int SocketReceivePollTime = 100000;
  21. private const int SocketSendPollTime = 5000;
  22. public NetEndPoint LocalEndPoint
  23. {
  24. get { return _localEndPoint; }
  25. }
  26. static NetSocket()
  27. {
  28. try
  29. {
  30. //Unity3d .NET 2.0 throws exception.
  31. // IPv6Support = Socket.OSSupportsIPv6;
  32. IPv6Support = false;
  33. }
  34. catch
  35. {
  36. IPv6Support = false;
  37. }
  38. }
  39. public NetSocket(NetManager.OnMessageReceived onMessageReceived)
  40. {
  41. _onMessageReceived = onMessageReceived;
  42. }
  43. private void ReceiveLogic(object state)
  44. {
  45. Socket socket = (Socket)state;
  46. EndPoint bufferEndPoint = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
  47. NetEndPoint bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint);
  48. byte[] receiveBuffer = new byte[NetConstants.PacketSizeLimit];
  49. while (_running)
  50. {
  51. //wait for data
  52. if (!socket.Poll(SocketReceivePollTime, SelectMode.SelectRead))
  53. {
  54. continue;
  55. }
  56. int result;
  57. //Reading data
  58. try
  59. {
  60. result = socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref bufferEndPoint);
  61. if (!bufferNetEndPoint.EndPoint.Equals(bufferEndPoint))
  62. {
  63. bufferNetEndPoint = new NetEndPoint((IPEndPoint)bufferEndPoint);
  64. }
  65. }
  66. catch (SocketException ex)
  67. {
  68. if (ex.SocketErrorCode == SocketError.ConnectionReset ||
  69. ex.SocketErrorCode == SocketError.MessageSize)
  70. {
  71. //10040 - message too long
  72. //10054 - remote close (not error)
  73. //Just UDP
  74. NetUtils.DebugWrite(ConsoleColor.DarkRed, "[R] Ingored error: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString() );
  75. continue;
  76. }
  77. NetUtils.DebugWriteError("[R]Error code: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString());
  78. _onMessageReceived(null, 0, (int)ex.SocketErrorCode, bufferNetEndPoint);
  79. continue;
  80. }
  81. //All ok!
  82. NetUtils.DebugWrite(ConsoleColor.Blue, "[R]Recieved data from {0}, result: {1}", bufferNetEndPoint.ToString(), result);
  83. _onMessageReceived(receiveBuffer, result, 0, bufferNetEndPoint);
  84. }
  85. }
  86. public bool Bind(int port, bool reuseAddress)
  87. {
  88. _udpSocketv4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  89. _udpSocketv4.Blocking = false;
  90. _udpSocketv4.ReceiveBufferSize = NetConstants.SocketBufferSize;
  91. _udpSocketv4.SendBufferSize = NetConstants.SocketBufferSize;
  92. _udpSocketv4.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, NetConstants.SocketTTL);
  93. if(reuseAddress)
  94. _udpSocketv4.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  95. #if !NETCORE
  96. _udpSocketv4.DontFragment = true;
  97. #endif
  98. try
  99. {
  100. _udpSocketv4.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  101. }
  102. catch (SocketException e)
  103. {
  104. NetUtils.DebugWriteError("Broadcast error: {0}", e.ToString());
  105. }
  106. if (!BindSocket(_udpSocketv4, new IPEndPoint(IPAddress.Any, port)))
  107. {
  108. return false;
  109. }
  110. _localEndPoint = new NetEndPoint((IPEndPoint)_udpSocketv4.LocalEndPoint);
  111. _running = true;
  112. _threadv4 = new Thread(ReceiveLogic);
  113. _threadv4.Name = "SocketThreadv4(" + port + ")";
  114. _threadv4.IsBackground = true;
  115. _threadv4.Start(_udpSocketv4);
  116. //Check IPv6 support
  117. if (!IPv6Support)
  118. return true;
  119. //Use one port for two sockets
  120. port = _localEndPoint.Port;
  121. _udpSocketv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
  122. _udpSocketv6.Blocking = false;
  123. _udpSocketv6.ReceiveBufferSize = NetConstants.SocketBufferSize;
  124. _udpSocketv6.SendBufferSize = NetConstants.SocketBufferSize;
  125. if (reuseAddress)
  126. _udpSocketv6.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  127. if (BindSocket(_udpSocketv6, new IPEndPoint(IPAddress.IPv6Any, port)))
  128. {
  129. _localEndPoint = new NetEndPoint((IPEndPoint)_udpSocketv6.LocalEndPoint);
  130. try
  131. {
  132. _udpSocketv6.SetSocketOption(
  133. SocketOptionLevel.IPv6,
  134. SocketOptionName.AddMembership,
  135. new IPv6MulticastOption(MulticastAddressV6));
  136. }
  137. catch(Exception)
  138. {
  139. // Unity3d throws exception - ignored
  140. }
  141. _threadv6 = new Thread(ReceiveLogic);
  142. _threadv6.Name = "SocketThreadv6(" + port + ")";
  143. _threadv6.IsBackground = true;
  144. _threadv6.Start(_udpSocketv6);
  145. }
  146. return true;
  147. }
  148. private bool BindSocket(Socket socket, IPEndPoint ep)
  149. {
  150. try
  151. {
  152. socket.Bind(ep);
  153. NetUtils.DebugWrite(ConsoleColor.Blue, "[B]Succesfully binded to port: {0}", ((IPEndPoint)socket.LocalEndPoint).Port);
  154. }
  155. catch (SocketException ex)
  156. {
  157. NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString());
  158. //TODO: very temporary hack for iOS (Unity3D)
  159. if (ex.SocketErrorCode == SocketError.AddressFamilyNotSupported)
  160. {
  161. return true;
  162. }
  163. return false;
  164. }
  165. return true;
  166. }
  167. public bool SendBroadcast(byte[] data, int offset, int size, int port)
  168. {
  169. try
  170. {
  171. int result = _udpSocketv4.SendTo(data, offset, size, SocketFlags.None, new IPEndPoint(IPAddress.Broadcast, port));
  172. if (result <= 0)
  173. return false;
  174. if (IPv6Support)
  175. {
  176. result = _udpSocketv6.SendTo(data, offset, size, SocketFlags.None, new IPEndPoint(MulticastAddressV6, port));
  177. if (result <= 0)
  178. return false;
  179. }
  180. }
  181. catch (Exception ex)
  182. {
  183. NetUtils.DebugWriteError("[S][MCAST]" + ex);
  184. return false;
  185. }
  186. return true;
  187. }
  188. public int SendTo(byte[] data, int offset, int size, NetEndPoint remoteEndPoint, ref int errorCode)
  189. {
  190. try
  191. {
  192. int result = 0;
  193. if (remoteEndPoint.EndPoint.AddressFamily == AddressFamily.InterNetwork)
  194. {
  195. if (!_udpSocketv4.Poll(SocketSendPollTime, SelectMode.SelectWrite))
  196. return -1;
  197. result = _udpSocketv4.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint.EndPoint);
  198. }
  199. else if(IPv6Support)
  200. {
  201. if (!_udpSocketv6.Poll(SocketSendPollTime, SelectMode.SelectWrite))
  202. return -1;
  203. result = _udpSocketv6.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint.EndPoint);
  204. }
  205. NetUtils.DebugWrite(ConsoleColor.Blue, "[S]Send packet to {0}, result: {1}", remoteEndPoint.EndPoint, result);
  206. return result;
  207. }
  208. catch (SocketException ex)
  209. {
  210. if (ex.SocketErrorCode != SocketError.MessageSize)
  211. {
  212. NetUtils.DebugWriteError("[S]" + ex);
  213. }
  214. errorCode = (int)ex.SocketErrorCode;
  215. return -1;
  216. }
  217. catch (Exception ex)
  218. {
  219. NetUtils.DebugWriteError("[S]" + ex);
  220. return -1;
  221. }
  222. }
  223. private void CloseSocket(Socket s)
  224. {
  225. #if NETCORE
  226. s.Dispose();
  227. #else
  228. s.Close();
  229. #endif
  230. }
  231. public void Close()
  232. {
  233. _running = false;
  234. //Close IPv4
  235. if (Thread.CurrentThread != _threadv4)
  236. {
  237. _threadv4.Join();
  238. }
  239. _threadv4 = null;
  240. if (_udpSocketv4 != null)
  241. {
  242. CloseSocket(_udpSocketv4);
  243. _udpSocketv4 = null;
  244. }
  245. //No ipv6
  246. if (_udpSocketv6 == null)
  247. return;
  248. //Close IPv6
  249. if (Thread.CurrentThread != _threadv6)
  250. {
  251. _threadv6.Join();
  252. }
  253. _threadv6 = null;
  254. if (_udpSocketv6 != null)
  255. {
  256. CloseSocket(_udpSocketv6);
  257. _udpSocketv6 = null;
  258. }
  259. }
  260. }
  261. }
  262. #else
  263. using System;
  264. using System.Collections.Generic;
  265. using System.IO;
  266. using System.Runtime.InteropServices.WindowsRuntime;
  267. using System.Threading;
  268. using System.Threading.Tasks;
  269. using Windows.Networking;
  270. using Windows.Networking.Sockets;
  271. using Windows.Storage.Streams;
  272. namespace FlyingWormConsole3.LiteNetLib
  273. {
  274. internal sealed class NetSocket
  275. {
  276. private DatagramSocket _datagramSocket;
  277. private readonly Dictionary<NetEndPoint, IOutputStream> _peers = new Dictionary<NetEndPoint, IOutputStream>();
  278. private readonly NetManager.OnMessageReceived _onMessageReceived;
  279. private readonly byte[] _byteBuffer = new byte[NetConstants.PacketSizeLimit];
  280. private readonly IBuffer _buffer;
  281. private NetEndPoint _bufferEndPoint;
  282. private NetEndPoint _localEndPoint;
  283. private static readonly HostName BroadcastAddress = new HostName("255.255.255.255");
  284. private static readonly HostName MulticastAddressV6 = new HostName(NetConstants.MulticastGroupIPv6);
  285. public NetEndPoint LocalEndPoint
  286. {
  287. get { return _localEndPoint; }
  288. }
  289. public NetSocket(NetManager.OnMessageReceived onMessageReceived)
  290. {
  291. _onMessageReceived = onMessageReceived;
  292. _buffer = _byteBuffer.AsBuffer();
  293. }
  294. private void OnMessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
  295. {
  296. var result = args.GetDataStream().ReadAsync(_buffer, _buffer.Capacity, InputStreamOptions.None).AsTask().Result;
  297. int length = (int)result.Length;
  298. if (length <= 0)
  299. return;
  300. if (_bufferEndPoint == null ||
  301. !_bufferEndPoint.HostName.IsEqual(args.RemoteAddress) ||
  302. !_bufferEndPoint.PortStr.Equals(args.RemotePort))
  303. {
  304. _bufferEndPoint = new NetEndPoint(args.RemoteAddress, args.RemotePort);
  305. }
  306. _onMessageReceived(_byteBuffer, length, 0, _bufferEndPoint);
  307. }
  308. public bool Bind(int port, bool reuseAddress)
  309. {
  310. _datagramSocket = new DatagramSocket();
  311. _datagramSocket.Control.InboundBufferSizeInBytes = NetConstants.SocketBufferSize;
  312. _datagramSocket.Control.DontFragment = true;
  313. _datagramSocket.Control.OutboundUnicastHopLimit = NetConstants.SocketTTL;
  314. _datagramSocket.MessageReceived += OnMessageReceived;
  315. try
  316. {
  317. _datagramSocket.BindServiceNameAsync(port.ToString()).AsTask().Wait();
  318. _datagramSocket.JoinMulticastGroup(MulticastAddressV6);
  319. _localEndPoint = new NetEndPoint(_datagramSocket.Information.LocalAddress, _datagramSocket.Information.LocalPort);
  320. }
  321. catch (Exception ex)
  322. {
  323. NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString());
  324. return false;
  325. }
  326. return true;
  327. }
  328. public bool SendBroadcast(byte[] data, int offset, int size, int port)
  329. {
  330. var portString = port.ToString();
  331. try
  332. {
  333. var outputStream =
  334. _datagramSocket.GetOutputStreamAsync(BroadcastAddress, portString)
  335. .AsTask()
  336. .Result;
  337. var writer = outputStream.AsStreamForWrite();
  338. writer.Write(data, offset, size);
  339. writer.Flush();
  340. outputStream =
  341. _datagramSocket.GetOutputStreamAsync(MulticastAddressV6, portString)
  342. .AsTask()
  343. .Result;
  344. writer = outputStream.AsStreamForWrite();
  345. writer.Write(data, offset, size);
  346. writer.Flush();
  347. }
  348. catch (Exception ex)
  349. {
  350. NetUtils.DebugWriteError("[S][MCAST]" + ex);
  351. return false;
  352. }
  353. return true;
  354. }
  355. public int SendTo(byte[] data, int offset, int length, NetEndPoint remoteEndPoint, ref int errorCode)
  356. {
  357. Task<uint> task = null;
  358. try
  359. {
  360. IOutputStream writer;
  361. if (!_peers.TryGetValue(remoteEndPoint, out writer))
  362. {
  363. writer =
  364. _datagramSocket.GetOutputStreamAsync(remoteEndPoint.HostName, remoteEndPoint.PortStr)
  365. .AsTask()
  366. .Result;
  367. _peers.Add(remoteEndPoint, writer);
  368. }
  369. task = writer.WriteAsync(data.AsBuffer(offset, length)).AsTask();
  370. return (int)task.Result;
  371. }
  372. catch (Exception ex)
  373. {
  374. if (task?.Exception?.InnerExceptions != null)
  375. {
  376. ex = task.Exception.InnerException;
  377. }
  378. var errorStatus = SocketError.GetStatus(ex.HResult);
  379. switch (errorStatus)
  380. {
  381. case SocketErrorStatus.MessageTooLong:
  382. errorCode = 10040;
  383. break;
  384. default:
  385. errorCode = (int)errorStatus;
  386. NetUtils.DebugWriteError("[S " + errorStatus + "(" + errorCode + ")]" + ex);
  387. break;
  388. }
  389. return -1;
  390. }
  391. }
  392. internal void RemovePeer(NetEndPoint ep)
  393. {
  394. _peers.Remove(ep);
  395. }
  396. public void Close()
  397. {
  398. _datagramSocket.Dispose();
  399. _datagramSocket = null;
  400. ClearPeers();
  401. }
  402. internal void ClearPeers()
  403. {
  404. _peers.Clear();
  405. }
  406. }
  407. }
  408. #endif
  409. #endif