forked from RevenantX/LiteNetLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetSocket.cs
More file actions
283 lines (254 loc) · 9.64 KB
/
NetSocket.cs
File metadata and controls
283 lines (254 loc) · 9.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace LiteNetLib
{
internal sealed class NetSocket
{
private Socket _udpSocketv4;
private Socket _udpSocketv6;
private Thread _threadv4;
private Thread _threadv6;
private bool _running;
private readonly NetManager.OnMessageReceived _onMessageReceived;
private static readonly IPAddress MulticastAddressV6 = IPAddress.Parse (NetConstants.MulticastGroupIPv6);
internal static readonly bool IPv6Support;
private const int SocketReceivePollTime = 100000;
private const int SocketSendPollTime = 1000;
public int LocalPort { get; private set; }
public short Ttl
{
get { return _udpSocketv4.Ttl; }
set
{
_udpSocketv4.Ttl = value;
}
}
static NetSocket()
{
#if UNITY_4 || UNITY_5 || UNITY_5_3_OR_NEWER
IPv6Support = Socket.SupportsIPv6;
#elif DISABLE_IPV6
IPv6Support = false;
#else
IPv6Support = Socket.OSSupportsIPv6;
#endif
}
public NetSocket(NetManager.OnMessageReceived onMessageReceived)
{
_onMessageReceived = onMessageReceived;
}
private void ReceiveLogic(object state)
{
Socket socket = (Socket)state;
EndPoint bufferEndPoint = new IPEndPoint(socket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
byte[] receiveBuffer = new byte[NetConstants.MaxPacketSize];
while (_running)
{
int result;
//Reading data
try
{
if (!socket.Poll(SocketReceivePollTime, SelectMode.SelectRead))
{
continue;
}
result = socket.ReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref bufferEndPoint);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.ConnectionReset ||
ex.SocketErrorCode == SocketError.MessageSize)
{
//10040 - message too long
//10054 - remote close (not error)
//Just UDP
NetUtils.DebugWrite(ConsoleColor.DarkRed, "[R] Ingored error: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString() );
continue;
}
NetUtils.DebugWriteError("[R]Error code: {0} - {1}", (int)ex.SocketErrorCode, ex.ToString());
_onMessageReceived(null, 0, (int) ex.SocketErrorCode, (IPEndPoint)bufferEndPoint);
continue;
}
//All ok!
NetUtils.DebugWrite(ConsoleColor.Blue, "[R]Received data from {0}, result: {1}", bufferEndPoint.ToString(), result);
_onMessageReceived(receiveBuffer, result, 0, (IPEndPoint)bufferEndPoint);
}
}
public bool Bind(IPAddress addressIPv4, IPAddress addressIPv6, int port, bool reuseAddress)
{
_udpSocketv4 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_udpSocketv4.Blocking = false;
_udpSocketv4.ReceiveBufferSize = NetConstants.SocketBufferSize;
_udpSocketv4.SendBufferSize = NetConstants.SocketBufferSize;
_udpSocketv4.Ttl = NetConstants.SocketTTL;
if(reuseAddress)
_udpSocketv4.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
#if !NETCORE
_udpSocketv4.DontFragment = true;
#endif
try
{
_udpSocketv4.EnableBroadcast = true;
}
catch (SocketException e)
{
NetUtils.DebugWriteError("Broadcast error: {0}", e.ToString());
}
if (!BindSocket(_udpSocketv4, new IPEndPoint(addressIPv4, port)))
{
return false;
}
LocalPort = ((IPEndPoint) _udpSocketv4.LocalEndPoint).Port;
_running = true;
_threadv4 = new Thread(ReceiveLogic);
_threadv4.Name = "SocketThreadv4(" + LocalPort + ")";
_threadv4.IsBackground = true;
_threadv4.Start(_udpSocketv4);
//Check IPv6 support
if (!IPv6Support)
return true;
_udpSocketv6 = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
_udpSocketv6.Blocking = false;
_udpSocketv6.ReceiveBufferSize = NetConstants.SocketBufferSize;
_udpSocketv6.SendBufferSize = NetConstants.SocketBufferSize;
//_udpSocketv6.Ttl = NetConstants.SocketTTL;
if (reuseAddress)
_udpSocketv6.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
//Use one port for two sockets
if (BindSocket(_udpSocketv6, new IPEndPoint(addressIPv6, LocalPort)))
{
try
{
#if !ENABLE_IL2CPP
_udpSocketv6.SetSocketOption(
SocketOptionLevel.IPv6,
SocketOptionName.AddMembership,
new IPv6MulticastOption(MulticastAddressV6));
#endif
}
catch(Exception)
{
// Unity3d throws exception - ignored
}
_threadv6 = new Thread(ReceiveLogic);
_threadv6.Name = "SocketThreadv6(" + LocalPort + ")";
_threadv6.IsBackground = true;
_threadv6.Start(_udpSocketv6);
}
return true;
}
private bool BindSocket(Socket socket, IPEndPoint ep)
{
try
{
socket.Bind(ep);
NetUtils.DebugWrite(ConsoleColor.Blue, "[B]Succesfully binded to port: {0}", ((IPEndPoint)socket.LocalEndPoint).Port);
}
catch (SocketException ex)
{
NetUtils.DebugWriteError("[B]Bind exception: {0}", ex.ToString());
//TODO: very temporary hack for iOS (Unity3D)
if (ex.SocketErrorCode == SocketError.AddressFamilyNotSupported)
{
return true;
}
return false;
}
return true;
}
public bool SendBroadcast(byte[] data, int offset, int size, int port)
{
bool success;
try
{
success = _udpSocketv4.SendTo(
data,
offset,
size,
SocketFlags.None,
new IPEndPoint(IPAddress.Broadcast, port)) > 0;
if (IPv6Support)
{
success = success || _udpSocketv6.SendTo(
data,
offset,
size,
SocketFlags.None,
new IPEndPoint(MulticastAddressV6, port)) > 0;
}
}
catch (Exception ex)
{
NetUtils.DebugWriteError("[S][MCAST]" + ex);
return false;
}
return success;
}
public int SendTo(byte[] data, int offset, int size, IPEndPoint remoteEndPoint, ref int errorCode)
{
try
{
var socket = _udpSocketv4;
if (remoteEndPoint.AddressFamily == AddressFamily.InterNetworkV6 && IPv6Support)
{
socket = _udpSocketv6;
}
int result;
if (!socket.Poll(SocketSendPollTime, SelectMode.SelectWrite))
return -1;
result = socket.SendTo(data, offset, size, SocketFlags.None, remoteEndPoint);
NetUtils.DebugWrite(ConsoleColor.Blue, "[S]Send packet to {0}, result: {1}", remoteEndPoint, result);
return result;
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
return 0;
}
if (ex.SocketErrorCode != SocketError.MessageSize)
{
NetUtils.DebugWriteError("[S]" + ex);
}
errorCode = (int)ex.SocketErrorCode;
return -1;
}
catch (Exception ex)
{
NetUtils.DebugWriteError("[S]" + ex);
return -1;
}
}
public void Close()
{
_running = false;
//Close IPv4
if (Thread.CurrentThread != _threadv4)
{
_threadv4.Join();
}
if (_udpSocketv4 != null)
{
_udpSocketv4.Close();
_udpSocketv4 = null;
}
_threadv4 = null;
//No ipv6
if (_udpSocketv6 == null)
return;
//Close IPv6
if (Thread.CurrentThread != _threadv6)
{
_threadv6.Join();
}
if (_udpSocketv6 != null)
{
_udpSocketv6.Close();
_udpSocketv6 = null;
}
_threadv6 = null;
}
}
}