forked from Elfocrash/L2dotNET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkClient.cs
More file actions
225 lines (190 loc) · 6.61 KB
/
NetworkClient.cs
File metadata and controls
225 lines (190 loc) · 6.61 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
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using log4net;
using L2dotNET.Utility;
namespace L2dotNET.Network
{
/// <summary>
/// Represents the method that will handle Client.OnConnected" event.
/// </summary>
public delegate void OnConnectedEventHandler(IPEndPoint endPoint, byte connectionId);
/// <summary>
/// Represents the method that will handle Client.OnDisconnected" event.
/// </summary>
public delegate void OnDisconnectedEventHandler(int errorCode, NetworkClient client, byte connectionId);
/// <summary>
/// Abstract class to all client connections.
/// </summary>
public abstract class NetworkClient
{
private static readonly ILog Log = LogManager.GetLogger(typeof(NetworkClient));
/// <summary>
/// Client <see cref="Socket"/>.
/// </summary>
public Socket MSocket;
/// <summary>
/// Send buffers queue.
/// </summary>
protected readonly Queue<byte[]> MSendQueue;
/// <summary>
/// Connection receive buffer.
/// </summary>
protected byte[] MReceiveBuffer;
/// <summary>
/// Receive callback.
/// </summary>
protected readonly AsyncCallback MReceiveCallback;
/// <summary>
/// Send callback.
/// </summary>
protected readonly AsyncCallback MSendCallback;
/// <summary>
/// Indicates if packet header was received.
/// </summary>
protected bool MHeaderReceived;
/// <summary>
/// Packet sending indicator.
/// </summary>
protected bool MSendStackFlag;
/// <summary>
/// Indicates if sending packet is aviable.
/// </summary>
protected bool MSendReadyFlag = true;
/// <summary>
/// Lock object.
/// </summary>
protected readonly object MLock = new object();
/// <summary>
/// Occurs after <see cref="NetworkClient"/> object was connected (initialized).
/// </summary>
public virtual event OnConnectedEventHandler OnConnected;
/// <summary>
/// Occurs after <see cref="NetworkClient"/> object was disconnected.
/// </summary>
public virtual event OnDisconnectedEventHandler OnDisconnected;
/// <summary>
/// Default connection buffer.
/// </summary>
protected static readonly byte[] MDefaultBuffer = new byte[4];
/// <summary>
/// Currently received packet capacity.
/// </summary>
protected int MReceivedLength;
/// <summary>
/// Connection id.
/// </summary>
public byte ConnectionId = 1;
/// <summary>
/// Initializes new instance of <see cref="NetworkClient"/> connection.
/// </summary>
protected NetworkClient()
{
MReceiveCallback = new AsyncCallback(ReceiveCallback);
MSendCallback = new AsyncCallback(SendCallback);
MSendQueue = new Queue<byte[]>();
MReceiveBuffer = MDefaultBuffer;
}
/// <summary>
/// Initializes new instance of <see cref="NetworkClient"/> connection.
/// </summary>
/// <param name="socket">Client <see cref="Socket"/> object.</param>
protected NetworkClient(Socket socket) : this()
{
Logger.WriteLine(Source.Debug, "Try set m_Socket");
try
{
MSocket = socket;
}
catch (Exception ex)
{
Logger.Exception(ex, "Try set m_Socket");
}
}
/// <summary>
/// Forces <see cref="NetworkClient"/> to begin receive from socket.
/// </summary>
public abstract void BeginReceive();
/// <summary>
/// Handles received <see cref="Packet"/>.
/// </summary>
/// <param name="packet">Received <see cref="Packet"/>.</param>
protected virtual void Handle(Packet packet)
{
Logger.WriteLine("Received (NC) :\r\n{0}", packet.ToString());
}
/// <summary>
/// Receive <see cref="AsyncCallback"/> method.
/// </summary>
protected abstract void ReceiveCallback(IAsyncResult ar);
/// <summary>
/// Send <see cref="AsyncCallback"/> method.
/// </summary>
protected virtual void SendCallback(IAsyncResult ar)
{
try
{
lock (MLock)
{
MSendReadyFlag = false;
while (!MSendReadyFlag && (MSendQueue.Count > 0))
{
byte[] buffer = MSendQueue.Dequeue();
MSocket.BeginSend(buffer, 0, buffer.Length, 0, MSendCallback, null);
}
MSendReadyFlag = true;
}
}
catch (Exception e)
{
Logger.Exception(e);
CloseConnection();
OnDisconnected?.Invoke(-1, this, ConnectionId);
}
}
/// <summary>
/// Serves for packet capacity validation and received buffer-><see cref="Packet"/> transforming.
/// </summary>
/// <param name="buffer">Received buffer.</param>
/// <param name="length">Received buffer capacity.</param>
public virtual void ReceiveData(byte[] buffer, int length) { }
/// <summary>
/// Sends buffer to client socket.
/// </summary>
/// <param name="buffer">Buffer to send.</param>
public virtual void SendData(byte[] buffer)
{
//#if DEBUG_NET_CLIENT
Log.Info($"Sending:\r\n{L2Buffer.ToString(buffer)}");
//#endif
if ((MSocket == null) || !MSocket.Connected)
return;
lock (MLock)
MSendQueue.Enqueue(buffer);
if (MSendReadyFlag)
SendCallback(null);
}
/// <summary>
/// Closes current client connection.
/// </summary>
public virtual void CloseConnection()
{
if ((MSocket == null) || !MSocket.Connected)
return;
try
{
MSocket.Shutdown(SocketShutdown.Both);
}
catch (Exception e)
{
Log.Info(e);
}
MSocket = null;
}
/// <summary>
/// Indicates if client socket is connected.
/// </summary>
public virtual bool Connected => (MSocket != null) && MSocket.Connected;
}
}