-
Notifications
You must be signed in to change notification settings - Fork 172
/
NetworkInterface.cs
237 lines (196 loc) · 6.32 KB
/
NetworkInterface.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
namespace KBEngine
{
using UnityEngine;
using System;
using System.Net.Sockets;
using System.Net;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using MessageID = System.UInt16;
using MessageLength = System.UInt16;
/// <summary>
/// 网络模块
/// 处理连接、收发数据
/// </summary>
public class NetworkInterface
{
public delegate void AsyncConnectMethod(ConnectState state);
public const int TCP_PACKET_MAX = 1460;
public delegate void ConnectCallback(string ip, int port, bool success, object userData);
protected Socket _socket = null;
PacketReceiver _packetReceiver = null;
PacketSender _packetSender = null;
public bool connected = false;
public class ConnectState
{
// for connect
public string connectIP = "";
public int connectPort = 0;
public ConnectCallback connectCB = null;
public AsyncConnectMethod caller = null;
public object userData = null;
public Socket socket = null;
public NetworkInterface networkInterface = null;
public string error = "";
}
public NetworkInterface()
{
reset();
}
~NetworkInterface()
{
Dbg.DEBUG_MSG("NetworkInterface::~NetworkInterface(), destructed!!!");
reset();
}
public virtual Socket sock()
{
return _socket;
}
public void reset()
{
if(valid())
{
if(_socket.RemoteEndPoint != null)
Dbg.DEBUG_MSG(string.Format("NetworkInterface::reset(), close socket from '{0}'", _socket.RemoteEndPoint.ToString()));
_socket.Close(0);
}
_socket = null;
_packetReceiver = null;
_packetSender = null;
connected = false;
}
public void close()
{
if(_socket != null)
{
_socket.Close(0);
_socket = null;
Event.fireAll("onDisconnected", new object[]{});
}
_socket = null;
connected = false;
}
public virtual PacketReceiver packetReceiver()
{
return _packetReceiver;
}
public virtual bool valid()
{
return ((_socket != null) && (_socket.Connected == true));
}
public void _onConnectionState(ConnectState state)
{
KBEngine.Event.deregisterIn(this);
bool success = (state.error == "" && valid());
if (success)
{
Dbg.DEBUG_MSG(string.Format("NetworkInterface::_onConnectionState(), connect to {0} is success!", state.socket.RemoteEndPoint.ToString()));
_packetReceiver = new PacketReceiver(this);
_packetReceiver.startRecv();
connected = true;
}
else
{
reset();
Dbg.ERROR_MSG(string.Format("NetworkInterface::_onConnectionState(), connect error! ip: {0}:{1}, err: {2}", state.connectIP, state.connectPort, state.error));
}
Event.fireAll("onConnectionState", new object[] { success });
if (state.connectCB != null)
state.connectCB(state.connectIP, state.connectPort, success, state.userData);
}
private static void connectCB(IAsyncResult ar)
{
ConnectState state = null;
try
{
// Retrieve the socket from the state object.
state = (ConnectState) ar.AsyncState;
// Complete the connection.
state.socket.EndConnect(ar);
Event.fireIn("_onConnectionState", new object[] { state });
}
catch (Exception e)
{
state.error = e.ToString();
Event.fireIn("_onConnectionState", new object[] { state });
}
}
/// <summary>
/// 在非主线程执行:连接服务器
/// </summary>
private void _asyncConnect(ConnectState state)
{
Dbg.DEBUG_MSG(string.Format("NetWorkInterface::_asyncConnect(), will connect to '{0}:{1}' ...", state.connectIP, state.connectPort));
try
{
state.socket.Connect(state.connectIP, state.connectPort);
}
catch (Exception e)
{
Dbg.ERROR_MSG(string.Format("NetWorkInterface::_asyncConnect(), connect to '{0}:{1}' fault! error = '{2}'", state.connectIP, state.connectPort, e));
state.error = e.ToString();
}
}
/// <summary>
/// 在非主线程执行:连接服务器结果回调
/// </summary>
private void _asyncConnectCB(IAsyncResult ar)
{
ConnectState state = (ConnectState)ar.AsyncState;
Dbg.DEBUG_MSG(string.Format("NetWorkInterface::_asyncConnectCB(), connect to '{0}:{1}' finish. error = '{2}'", state.connectIP, state.connectPort, state.error));
// Call EndInvoke to retrieve the results.
state.caller.EndInvoke(ar);
Event.fireIn("_onConnectionState", new object[] { state });
}
public void connectTo(string ip, int port, ConnectCallback callback, object userData)
{
if (valid())
throw new InvalidOperationException("Have already connected!");
if (!(new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))")).IsMatch(ip))
{
IPHostEntry ipHost = Dns.GetHostEntry(ip);
ip = ipHost.AddressList[0].ToString();
}
// Security.PrefetchSocketPolicy(ip, 843);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, KBEngineApp.app.getInitArgs().getRecvBufferSize() * 2);
_socket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, SocketOptionName.SendBuffer, KBEngineApp.app.getInitArgs().getSendBufferSize() * 2);
_socket.NoDelay = true;
//_socket.Blocking = false;
AsyncConnectMethod asyncConnectMethod = new AsyncConnectMethod(this._asyncConnect);
ConnectState state = new ConnectState();
state.connectIP = ip;
state.connectPort = port;
state.connectCB = callback;
state.userData = userData;
state.socket = _socket;
state.networkInterface = this;
state.caller = asyncConnectMethod;
Dbg.DEBUG_MSG("connect to " + ip + ":" + port + " ...");
connected = false;
// 先注册一个事件回调,该事件在当前线程触发
Event.registerIn("_onConnectionState", this, "_onConnectionState");
asyncConnectMethod.BeginInvoke(state, new AsyncCallback(this._asyncConnectCB), state);
}
public bool send(MemoryStream stream)
{
if (!valid())
{
throw new ArgumentException("invalid socket!");
}
if (_packetSender == null)
_packetSender = new PacketSender(this);
return _packetSender.send(stream);
}
public void process()
{
if (!valid())
return;
if (_packetReceiver != null)
_packetReceiver.process();
}
}
}