有点卡在这个我...
设想:
一个套接字处理游戏模拟器,用于发送和接收以 VL64 和其他字符串编码的编码数据。需要支持大约 4000 个套接字请求等。
目前它使用 AsyncCallback 来执行异步服务器角色等。
代码:
private static SnowTcpListener mServer;
mServer = new SnowTcpListener(new IPEndPoint(IPAddress.Any, "IP"), backlog, new OnNewConnectionCallback(SessionManager.HandleIncomingConnection));
Backlog 是 Socket backlog 的 int。
SnowTcp 监听器
/// <summary>
/// Callback to be invoked upon accepting a new connection.
/// </summary>
/// <param name="Socket">Incoming socket connection</param>
public delegate void OnNewConnectionCallback(Socket Socket);
/// <summary>
/// Reality simple asynchronous TCP listener.
/// </summary>
public class SnowTcpListener : IDisposable // Snow prefix to avoid conflicts with System.Net.TcpListener
{
private Socket mSocket;
private OnNewConnectionCallback mCallback;
public SnowTcpListener(IPEndPoint LocalEndpoint, int Backlog, OnNewConnectionCallback Callback)
{
mCallback = Callback;
mSocket = new Socket(LocalEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
mSocket.Bind(LocalEndpoint);
mSocket.Listen(Backlog);
BeginAccept();
}
public void Dispose()
{
if (mSocket != null)
{
mSocket.Dispose();
mSocket = null;
}
}
private void BeginAccept()
{
try
{
mSocket.BeginAccept(OnAccept, mSocket);
}
catch (Exception) { }
}
private void OnAccept(IAsyncResult Result)
{
try
{
Socket ResultSocket = (Socket)mSocket.EndAccept(Result);
mCallback.Invoke(ResultSocket);
}
catch (Exception) { }
BeginAccept();
}
SessionManager.HandleIncomingConnection:
public static void HandleIncomingConnection(Socket IncomingSocket)
{
bool Reject = ModerationBanManager.IsRemoteAddressBlacklisted(IncomingSocket.RemoteEndPoint.ToString().Split(':')[0]);
Output.WriteLine((Reject ? "Rejected" : "Accepted") + " incoming connection from " + IncomingSocket.RemoteEndPoint.ToString() + ".",
OutputLevel.Informational);
if (Reject)
{
try
{
IncomingSocket.Close();
}
catch (Exception) { }
return;
}
lock (mSyncRoot)
{
uint Id = mCounter++;
mSessions.Add(Id, new Session(Id, IncomingSocket));
}
}
然后它创建一个新的“会话”
public Session(uint Id, Socket Socket)
{
mId = Id;
mSocket = Socket;
mBuffer = new byte[512];
mPongOk = true;
mSocket.SendBufferSize = 512;
BeginReceive();
}
哪个反过来调用 BeginRecieve()
private void BeginReceive()
{
try
{
if (mSocket != null)
{
//TODO: BeginRecieve();
mSocket.BeginReceive(mBuffer, 0, mBuffer.Length, SocketFlags.None, new AsyncCallback(OnReceiveData), mSocket);
}
}
catch (Exception)
{
SessionManager.StopSession(mId);
}
}
OnRecieveData()
private void OnReceiveData(IAsyncResult Result)
{
int ByteCount = 0;
try
{
if (mSocket != null)
{
ByteCount = mSocket.EndReceive(Result);
}
}
catch (Exception) { }
if (ByteCount < 1 || ByteCount >= mBuffer.Length)
{
SessionManager.StopSession(mId);
return;
}
ProcessData(ByteUtil.ChompBytes(mBuffer, 0, ByteCount));
BeginReceive();
}
如果您需要更多代码,请询问。
我将如何创建它以使连接位于单独的线程中,或者我将如何改善我的套接字体验,就像获得一定数量的会话一样,它只是滞后了。我试图增加缓冲区,但它使情况变得更糟。
我现在已经走到了尽头,我已经尝试了几乎所有我能想到的东西,我真的可以在一些帮助下做!
感谢您阅读这篇很长的帖子,如果问题不清楚,请尝试让您更清楚!
干杯迈克