Refactoring of BNetServer
This commit is contained in:
@@ -25,12 +25,15 @@ namespace Framework.Networking
|
||||
|
||||
public class AsyncAcceptor
|
||||
{
|
||||
TcpListener _listener;
|
||||
volatile bool _closed;
|
||||
|
||||
public bool Start(string ip, int port)
|
||||
{
|
||||
IPAddress bindIP;
|
||||
if (!IPAddress.TryParse(ip, out bindIP))
|
||||
{
|
||||
Log.outError(LogFilter.Network, "Server can't be started: Invalid IP-Address ({0})", ip);
|
||||
Log.outError(LogFilter.Network, $"Server can't be started: Invalid IP-Address: {ip}");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -73,8 +76,5 @@ namespace Framework.Networking
|
||||
_closed = true;
|
||||
_listener.Stop();
|
||||
}
|
||||
|
||||
TcpListener _listener;
|
||||
volatile bool _closed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,14 @@ namespace Framework.Networking
|
||||
{
|
||||
public class NetworkThread<TSocketType> where TSocketType : ISocket
|
||||
{
|
||||
int _connections;
|
||||
volatile bool _stopped;
|
||||
|
||||
Thread _thread;
|
||||
|
||||
List<TSocketType> _Sockets = new List<TSocketType>();
|
||||
List<TSocketType> _newSockets = new List<TSocketType>();
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_stopped = true;
|
||||
@@ -56,6 +64,7 @@ namespace Framework.Networking
|
||||
}
|
||||
|
||||
protected virtual void SocketAdded(TSocketType sock) { }
|
||||
|
||||
protected virtual void SocketRemoved(TSocketType sock) { }
|
||||
|
||||
void AddNewSockets()
|
||||
@@ -114,13 +123,5 @@ namespace Framework.Networking
|
||||
_newSockets.Clear();
|
||||
_Sockets.Clear();
|
||||
}
|
||||
|
||||
int _connections;
|
||||
volatile bool _stopped;
|
||||
|
||||
Thread _thread;
|
||||
|
||||
List<TSocketType> _Sockets = new List<TSocketType>();
|
||||
List<TSocketType> _newSockets = new List<TSocketType>();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,46 +20,56 @@ using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Framework.Networking
|
||||
{
|
||||
public abstract class SSLSocket : ISocket
|
||||
public abstract class SSLSocket : ISocket, IDisposable
|
||||
{
|
||||
Socket _socket;
|
||||
internal SslStream _stream;
|
||||
IPEndPoint _remoteEndPoint;
|
||||
byte[] _receiveBuffer;
|
||||
|
||||
protected SSLSocket(Socket socket)
|
||||
{
|
||||
_socket = socket;
|
||||
_remoteAddress = ((IPEndPoint)_socket.RemoteEndPoint).Address;
|
||||
_remotePort = (ushort)((IPEndPoint)_socket.RemoteEndPoint).Port;
|
||||
_remoteEndPoint = (IPEndPoint)_socket.RemoteEndPoint;
|
||||
_receiveBuffer = new byte[ushort.MaxValue];
|
||||
|
||||
_stream = new SslStream(new NetworkStream(socket), false);
|
||||
}
|
||||
|
||||
public abstract void Start();
|
||||
public virtual void Dispose()
|
||||
{
|
||||
_receiveBuffer = null;
|
||||
_stream.Dispose();
|
||||
}
|
||||
|
||||
public abstract void Accept();
|
||||
|
||||
public virtual bool Update()
|
||||
{
|
||||
return IsOpen();
|
||||
return _socket.Connected;
|
||||
}
|
||||
|
||||
public IPAddress GetRemoteIpAddress()
|
||||
public IPEndPoint GetRemoteIpEndPoint()
|
||||
{
|
||||
return _remoteAddress;
|
||||
return _remoteEndPoint;
|
||||
}
|
||||
|
||||
public ushort GetRemotePort()
|
||||
{
|
||||
return _remotePort;
|
||||
}
|
||||
|
||||
public void AsyncRead()
|
||||
public async Task AsyncRead()
|
||||
{
|
||||
if (!IsOpen())
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
_stream.BeginRead(_receiveBuffer, 0, _receiveBuffer.Length, ReadHandlerInternal, _stream);
|
||||
var result = await _stream.ReadAsync(_receiveBuffer, 0, _receiveBuffer.Length);
|
||||
|
||||
byte[] data = new byte[result];
|
||||
Buffer.BlockCopy(_receiveBuffer, 0, data, 0, result);
|
||||
ReadHandler(data, result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -67,28 +77,11 @@ namespace Framework.Networking
|
||||
}
|
||||
}
|
||||
|
||||
void ReadHandlerInternal(IAsyncResult result)
|
||||
{
|
||||
int bytes = 0;
|
||||
try
|
||||
{
|
||||
bytes = _stream.EndRead(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.outException(ex);
|
||||
}
|
||||
|
||||
ReadHandler(bytes);
|
||||
}
|
||||
|
||||
public abstract void ReadHandler(int transferredBytes);
|
||||
|
||||
public void AsyncHandshake(X509Certificate2 certificate)
|
||||
public async Task AsyncHandshake(X509Certificate2 certificate)
|
||||
{
|
||||
try
|
||||
{
|
||||
_stream.AuthenticateAsServer(certificate, false, System.Security.Authentication.SslProtocols.Tls, false);
|
||||
await _stream.AuthenticateAsServerAsync(certificate, false, System.Security.Authentication.SslProtocols.Tls, false);
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
@@ -96,17 +89,20 @@ namespace Framework.Networking
|
||||
CloseSocket();
|
||||
return;
|
||||
}
|
||||
AsyncRead();
|
||||
|
||||
await AsyncRead();
|
||||
}
|
||||
|
||||
public void AsyncWrite(byte[] data)
|
||||
public abstract void ReadHandler(byte[] data, int receivedLength);
|
||||
|
||||
public async Task AsyncWrite(byte[] data)
|
||||
{
|
||||
if (!IsOpen())
|
||||
return;
|
||||
|
||||
try
|
||||
{
|
||||
_stream.Write(data, 0, data.Length);
|
||||
await _stream.WriteAsync(data, 0, data.Length);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -118,39 +114,22 @@ namespace Framework.Networking
|
||||
{
|
||||
try
|
||||
{
|
||||
_closed = true;
|
||||
_socket.Shutdown(SocketShutdown.Both);
|
||||
_socket.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.outDebug(LogFilter.Network, "WorldSocket.CloseSocket: {0} errored when shutting down socket: {1}", GetRemoteIpAddress().ToString(), ex.Message);
|
||||
Log.outDebug(LogFilter.Network, $"WorldSocket.CloseSocket: {GetRemoteIpEndPoint()} errored when shutting down socket: {ex.Message}");
|
||||
}
|
||||
|
||||
OnClose();
|
||||
}
|
||||
|
||||
public virtual void OnClose() { Dispose(); }
|
||||
|
||||
public bool IsOpen() { return _socket.Connected; }
|
||||
|
||||
public void SetNoDelay(bool enable)
|
||||
{
|
||||
_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, enable);
|
||||
}
|
||||
|
||||
public virtual void OnClose() { }
|
||||
|
||||
public bool IsOpen() { return !_closed; }
|
||||
|
||||
public byte[] GetReceiveBuffer()
|
||||
{
|
||||
return _receiveBuffer;
|
||||
}
|
||||
|
||||
Socket _socket;
|
||||
internal SslStream _stream;
|
||||
byte[] _receiveBuffer;
|
||||
|
||||
volatile bool _closed;
|
||||
|
||||
IPAddress _remoteAddress;
|
||||
ushort _remotePort;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,42 +18,50 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Framework.Networking
|
||||
{
|
||||
public interface ISocket
|
||||
{
|
||||
void Accept();
|
||||
bool Update();
|
||||
bool IsOpen();
|
||||
void CloseSocket();
|
||||
}
|
||||
|
||||
public abstract class SocketBase : ISocket, IDisposable
|
||||
{
|
||||
Socket _socket;
|
||||
IPEndPoint _remoteIPEndPoint;
|
||||
byte[] _receiveBuffer;
|
||||
|
||||
protected SocketBase(Socket socket)
|
||||
{
|
||||
_socket = socket;
|
||||
_remoteAddress = ((IPEndPoint)_socket.RemoteEndPoint).Address;
|
||||
_remotePort = (ushort)((IPEndPoint)_socket.RemoteEndPoint).Port;
|
||||
_remoteIPEndPoint = (IPEndPoint)_socket.RemoteEndPoint;
|
||||
_receiveBuffer = new byte[ushort.MaxValue];
|
||||
}
|
||||
|
||||
public virtual void Dispose()
|
||||
{
|
||||
_receiveBuffer = null;
|
||||
_socket.Dispose();
|
||||
}
|
||||
|
||||
public abstract void Start();
|
||||
public abstract void Accept();
|
||||
|
||||
public virtual bool Update()
|
||||
{
|
||||
return IsOpen();
|
||||
}
|
||||
|
||||
public IPAddress GetRemoteIpAddress()
|
||||
public IPEndPoint GetRemoteIpAddress()
|
||||
{
|
||||
return _remoteAddress;
|
||||
return _remoteIPEndPoint;
|
||||
}
|
||||
|
||||
public ushort GetRemotePort()
|
||||
{
|
||||
return _remotePort;
|
||||
}
|
||||
|
||||
public void AsyncRead()
|
||||
public async Task AsyncRead()
|
||||
{
|
||||
if (!IsOpen())
|
||||
return;
|
||||
@@ -63,12 +71,12 @@ namespace Framework.Networking
|
||||
using (var socketEventargs = new SocketAsyncEventArgs())
|
||||
{
|
||||
socketEventargs.SetBuffer(_receiveBuffer, 0, _receiveBuffer.Length);
|
||||
socketEventargs.Completed += (sender, args) => ReadHandlerInternal(args);
|
||||
socketEventargs.Completed += async (sender, args) => await ProcessReadAsync(args);
|
||||
socketEventargs.SocketFlags = SocketFlags.None;
|
||||
socketEventargs.RemoteEndPoint = _socket.RemoteEndPoint;
|
||||
|
||||
if (!_socket.ReceiveAsync(socketEventargs))
|
||||
ReadHandlerInternal(socketEventargs);
|
||||
await ProcessReadAsync(socketEventargs);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -77,8 +85,7 @@ namespace Framework.Networking
|
||||
}
|
||||
}
|
||||
|
||||
public delegate void SocketReadCallback(SocketAsyncEventArgs args);
|
||||
public void AsyncReadWithCallback(SocketReadCallback callback)
|
||||
public async Task AsyncReadWithCallback(SocketReadCallback callback)
|
||||
{
|
||||
if (!IsOpen())
|
||||
return;
|
||||
@@ -92,7 +99,7 @@ namespace Framework.Networking
|
||||
socketEventargs.UserToken = _socket;
|
||||
socketEventargs.SocketFlags = SocketFlags.None;
|
||||
if (!_socket.ReceiveAsync(socketEventargs))
|
||||
callback(socketEventargs);
|
||||
await callback(socketEventargs);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -101,7 +108,7 @@ namespace Framework.Networking
|
||||
}
|
||||
}
|
||||
|
||||
void ReadHandlerInternal(SocketAsyncEventArgs args)
|
||||
async Task ProcessReadAsync(SocketAsyncEventArgs args)
|
||||
{
|
||||
if (args.SocketError != SocketError.Success)
|
||||
{
|
||||
@@ -115,31 +122,19 @@ namespace Framework.Networking
|
||||
return;
|
||||
}
|
||||
|
||||
ReadHandler(args.BytesTransferred);
|
||||
byte[] data = new byte[args.BytesTransferred];
|
||||
Buffer.BlockCopy(_receiveBuffer, 0, data, 0, args.BytesTransferred);
|
||||
await ReadHandler(data, args.BytesTransferred);
|
||||
}
|
||||
|
||||
public abstract void ReadHandler(int transferredBytes);
|
||||
public abstract Task ReadHandler(byte[] data, int bytesTransferred);
|
||||
|
||||
public void AsyncWrite(byte[] data)
|
||||
public async void AsyncWrite(byte[] data)
|
||||
{
|
||||
if (!IsOpen())
|
||||
return;
|
||||
|
||||
using (var socketEventargs = new SocketAsyncEventArgs())
|
||||
{
|
||||
socketEventargs.SetBuffer(data, 0, data.Length);
|
||||
socketEventargs.Completed += WriteHandlerInternal;
|
||||
socketEventargs.RemoteEndPoint = _socket.RemoteEndPoint;
|
||||
socketEventargs.UserToken = _socket;
|
||||
socketEventargs.SocketFlags = SocketFlags.None;
|
||||
|
||||
_socket.SendAsync(socketEventargs);
|
||||
}
|
||||
}
|
||||
|
||||
void WriteHandlerInternal(object sender, SocketAsyncEventArgs args)
|
||||
{
|
||||
args.Completed -= WriteHandlerInternal;
|
||||
await _socket.SendAsync(data, SocketFlags.None);
|
||||
}
|
||||
|
||||
public void CloseSocket()
|
||||
@@ -149,46 +144,26 @@ namespace Framework.Networking
|
||||
|
||||
try
|
||||
{
|
||||
_closed = true;
|
||||
_socket.Shutdown(SocketShutdown.Both);
|
||||
_socket.Close();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.outDebug(LogFilter.Network, "WorldSocket.CloseSocket: {0} errored when shutting down socket: {1}", GetRemoteIpAddress().ToString(), ex.Message);
|
||||
Log.outDebug(LogFilter.Network, $"WorldSocket.CloseSocket: {GetRemoteIpAddress()} errored when shutting down socket: {ex.Message}");
|
||||
}
|
||||
|
||||
OnClose();
|
||||
}
|
||||
|
||||
public virtual void OnClose() { Dispose(); }
|
||||
|
||||
public bool IsOpen() { return _socket.Connected; }
|
||||
|
||||
public void SetNoDelay(bool enable)
|
||||
{
|
||||
_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, enable);
|
||||
}
|
||||
|
||||
public virtual void OnClose() { Dispose(); }
|
||||
|
||||
public bool IsOpen() { return !_closed; }
|
||||
|
||||
public byte[] GetReceiveBuffer()
|
||||
{
|
||||
return _receiveBuffer;
|
||||
}
|
||||
|
||||
Socket _socket;
|
||||
byte[] _receiveBuffer;
|
||||
|
||||
volatile bool _closed;
|
||||
|
||||
IPAddress _remoteAddress;
|
||||
ushort _remotePort;
|
||||
}
|
||||
|
||||
public interface ISocket
|
||||
{
|
||||
void Start();
|
||||
bool Update();
|
||||
bool IsOpen();
|
||||
void CloseSocket();
|
||||
public delegate Task SocketReadCallback(SocketAsyncEventArgs args);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,10 @@ namespace Framework.Networking
|
||||
{
|
||||
public class SocketManager<TSocketType> where TSocketType : ISocket
|
||||
{
|
||||
public AsyncAcceptor Acceptor;
|
||||
NetworkThread<TSocketType>[] _threads;
|
||||
int _threadCount;
|
||||
|
||||
public virtual bool StartNetwork(string bindIp, int port, int threadCount = 1)
|
||||
{
|
||||
Cypher.Assert(threadCount > 0);
|
||||
@@ -74,7 +78,7 @@ namespace Framework.Networking
|
||||
try
|
||||
{
|
||||
TSocketType newSocket = (TSocketType)Activator.CreateInstance(typeof(TSocketType), sock);
|
||||
newSocket.Start();
|
||||
newSocket.Accept();
|
||||
|
||||
_threads[SelectThreadWithMinConnections()].AddSocket(newSocket);
|
||||
}
|
||||
@@ -96,9 +100,5 @@ namespace Framework.Networking
|
||||
|
||||
return min;
|
||||
}
|
||||
|
||||
public AsyncAcceptor Acceptor;
|
||||
NetworkThread<TSocketType>[] _threads;
|
||||
int _threadCount;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user