套接字 - 你能把它换成另一个线程吗?

时间:2012-12-23 23:25:03

标签: c# sockets

有点困在我身上......

情景:

套接字处理游戏模拟器,用于发送和接收以VL64和其他字符串编码的编码数据。需要支持大约4000个套接字请求等。

目前它使用AsyncCallback来执行异步服务器角色等。

代码:

private static SnowTcpListener mServer;

mServer = new SnowTcpListener(new IPEndPoint(IPAddress.Any, "IP"), backlog, new OnNewConnectionCallback(SessionManager.HandleIncomingConnection));

Backlog是Socket积压的一个int。

SnowTcpListener

/// <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();
        }

如果您需要更多代码,请询问。

我将如何创建它,以便连接在一个单独的线程中,或者我将如何改善我的套接字体验,就像进入一定数量的会话一样,它只是滞后。我试图增加缓冲区,但它使情况变得更糟。

我现在已经走到了我的绳索的尽头,我已经尝试了几乎所有我能想到的东西,而且我真的可以帮到它!

感谢您阅读这篇非常长的帖子,如果问题不明确,请尝试让您更清楚!

干杯 麦克

1 个答案:

答案 0 :(得分:1)

您在评估现有代码中的瓶颈和性能问题方面做了哪些工作?您是否使用任何工具对其进行了分析?

从目前发布的代码中,您只是异步接收新连接(BeginAccept)和传入数据(BeginReceive)。这些都不会导致任何性能下降。但是BeginReceive函数调用“ProcessData”,这可能是所有业务逻辑用于处理消息的地方。我怀疑这是你的瓶颈所在。但这只是猜测。

你说4000个套接字,所以“每个连接的线程”听起来不像正确的设计。

但是因为你已经在做异步套接字,所以正确的方法似乎是在工作池线程中调用ProcessData。当ProcessData完成时,只需在该会话对象上再次调用BeginReceive。如下所示:

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;
    }

    ThreadPool.QueueUserWorkItem(ProcessDataInThread, ByteCount);

}

void ProcessDataInThread(object context)
{
    int ByteCount = (int)context;

    ProcessData(ByteUtil.ChompBytes(mBuffer, 0, ByteCount));
    BeginReceive();
}