forked from hellogavin/UnityUtils
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PackageSocket.cs
332 lines (279 loc) · 7.35 KB
/
PackageSocket.cs
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
using UnityEngine;
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
public enum PackageSocketError
{
None,
SocketShutdown,
RecviveBufferNotEnough,
RecviveTimeout,
}
public class PackageSocket
{
enum State
{
Closed,
Connecting,
Connected,
UserClosed,
Error,
}
public delegate void ConnectCallback(bool connected);
public delegate void RecviveCallback(byte[] data, int start, int length);
public delegate void DisconnectCallback(SocketError socketError, PackageSocketError packageSocketError);
public ConnectCallback OnConnect;
public RecviveCallback OnRecvive;
public DisconnectCallback OnDisconnect;
public int ConnectTimeoutSetting = 3000;
public int ReceiveTimeoutSetting = 10000;
public int AutoSendPingSetting = 10000 / 3;
private State CurState;
private DateTime CheckTimeout;
private Socket CurSocket;
private SocketError LastSystemSocketError;
private PackageSocketError LastPackageSocketError;
private Queue<byte[]> SendQueue;
private int SendQueueStartIndex;
private byte[] RecvBuffer;
private int RecvBufferBeginIndex;
private int RecvBufferEndIndex;
private byte[] PingBuffer;
private DateTime NextSendPingTime;
const int MaxSizePerSend = 1024 * 4;
public PackageSocket()
{
SendQueue = new Queue<byte[]>();
RecvBuffer = new byte[(int)ushort.MaxValue + 2];
Reset();
}
public void Connect(string ip, int port)
{
Reset();
CurSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
CurSocket.Blocking = false;
try
{
var ipAddress = IPAddress.Parse(ip);
CurSocket.Connect(ipAddress, port);
}
catch (SocketException e)
{
if (e.SocketErrorCode != SocketError.WouldBlock && e.SocketErrorCode != SocketError.InProgress)
throw e;
}
CurState = State.Connecting;
CheckTimeout = DateTime.Now.AddMilliseconds(ConnectTimeoutSetting);
}
public void Close()
{
if (CurState != State.Closed)
{
CurState = State.UserClosed;
}
}
public void Update()
{
switch (CurState)
{
case State.Closed:
return;
case State.Connecting:
ProcessConnect();
break;
case State.Connected:
ProcessSend();
ProcessReceive();
break;
case State.Error:
Reset();
OnDisconnect(LastSystemSocketError, LastPackageSocketError);
break;
case State.UserClosed:
Reset();
break;
}
}
public void Send(Byte[] buffer, int start, int length)
{
var headerLen = GetHeaderLength();
var data = new byte[headerLen + length];
EncodeHeader(length, data, 0);
Array.Copy(buffer, start, data, headerLen, length);
SendQueue.Enqueue(data);
if (CurState == State.Connected)
ProcessSend();
}
public void SendPing()
{
if (PingBuffer == null)
{
var headerLen = GetHeaderLength();
PingBuffer = new byte[headerLen];
EncodeHeader(0, PingBuffer, 0);
}
SendQueue.Enqueue(PingBuffer);
ProcessSend();
}
void ProcessConnect()
{
var now = DateTime.Now;
// http://www.dpull.com/blog/csharp_socket/
CurSocket.Poll(0, SelectMode.SelectWrite);
if (!CurSocket.Connected && CheckTimeout < now)
{
Reset();
OnConnect(false);
}
else if (CurSocket.Connected)
{
OnConnect(true);
CurState = State.Connected;
CheckTimeout = now.AddMilliseconds(ReceiveTimeoutSetting);
}
}
void ProcessSend()
{
if (!CurSocket.Poll(0, SelectMode.SelectWrite))
return;
while (CurState == State.Connected && SendQueue.Count > 0)
{
var buffer = SendQueue.Peek();
int leftLength = buffer.Length - SendQueueStartIndex;
while (leftLength > 0)
{
var trySend = Math.Min(MaxSizePerSend, leftLength);
SocketError error;
var send = CurSocket.Send(buffer, SendQueueStartIndex, trySend, SocketFlags.None, out error);
if (error != SocketError.Success)
{
if (error != SocketError.WouldBlock && error != SocketError.Interrupted && error != SocketError.TryAgain)
{
SetError(error, PackageSocketError.None);
return;
}
break;
}
SendQueueStartIndex += send;
leftLength -= send;
}
if (leftLength == 0)
{
SendQueue.Dequeue();
SendQueueStartIndex = 0;
}
}
}
void ProcessReceive()
{
var now = DateTime.Now;
if (!CurSocket.Poll(0, SelectMode.SelectRead))
{
if (NextSendPingTime < now)
{
SendPing();
NextSendPingTime = now.AddMilliseconds(AutoSendPingSetting);
}
if (CheckTimeout < now)
SetError(SocketError.Success, PackageSocketError.RecviveTimeout);
return;
}
while (CurState == State.Connected)
{
var leftBufferSize = RecvBuffer.Length - RecvBufferEndIndex;
SocketError error;
var receive = CurSocket.Receive(RecvBuffer, RecvBufferEndIndex, leftBufferSize, SocketFlags.None, out error);
if (error != SocketError.Success)
{
if (error != SocketError.WouldBlock && error != SocketError.Interrupted && error != SocketError.TryAgain)
SetError(error, PackageSocketError.None);
break;
}
RecvBufferEndIndex += receive;
ProcessPackage();
if (receive == 0)
{
SetError(error, PackageSocketError.SocketShutdown);
break;
}
CheckTimeout = now.AddMilliseconds(ReceiveTimeoutSetting);
NextSendPingTime = now.AddMilliseconds(AutoSendPingSetting);
}
}
void ProcessPackage()
{
while (CurState == State.Connected)
{
var bufferLen = RecvBufferEndIndex - RecvBufferBeginIndex;
var dataLen = 0;
var headerLen = DecodeHeader(RecvBuffer, RecvBufferBeginIndex, bufferLen, ref dataLen);
if (headerLen == 0)
{
headerLen = GetHeaderLength();
if (RecvBufferBeginIndex + headerLen > RecvBuffer.Length)
MemmoveRecvBuffer();
break;
}
var packageLen = headerLen + dataLen;
if (packageLen > RecvBuffer.Length)
{
SetError(SocketError.Success, PackageSocketError.RecviveBufferNotEnough);
break;
}
if (packageLen <= bufferLen)
{
if (dataLen > 0)
OnRecvive(RecvBuffer, RecvBufferBeginIndex + headerLen, dataLen);
RecvBufferBeginIndex += packageLen;
continue;
}
if (RecvBufferBeginIndex + packageLen > RecvBuffer.Length)
MemmoveRecvBuffer();
break;
}
}
public void MemmoveRecvBuffer()
{
var bufferLen = RecvBufferEndIndex - RecvBufferBeginIndex;
Array.Copy(RecvBuffer, RecvBufferBeginIndex, RecvBuffer, 0, bufferLen);
RecvBufferBeginIndex = 0;
RecvBufferEndIndex = bufferLen;
}
void SetError(SocketError socketError, PackageSocketError packageSocketError)
{
LastSystemSocketError = socketError;
LastPackageSocketError = packageSocketError;
CurState = State.Error;
}
void Reset()
{
CurState = State.Closed;
CurSocket = null;
RecvBufferBeginIndex = 0;
RecvBufferEndIndex = 0;
SendQueue.Clear();
SendQueueStartIndex = 0;
}
protected virtual int DecodeHeader(byte[] buffer, int start, int length, ref int dataLength)
{
if (length < 2)
return 0;
dataLength = buffer[start] << 8 | buffer[start + 1];
return 2;
}
protected virtual void EncodeHeader(int length, byte[] buffer, int start)
{
buffer[start + 0] = (byte)((length >> 8) & 0xff);
buffer[start + 1] = (byte)(length & 0xff);
}
protected virtual int GetHeaderLength()
{
return 2;
}
public override string ToString ()
{
return string.Format("State:{0} SendQueue:{1}", CurState, SendQueue.Count);
}
}