异步套接字侦听器为某些客户端接收数据的时间非常晚

时间:2014-09-06 06:08:22

标签: c# serversocket

我使用异步方法在c#中创建服务器套接字。这是我正在使用的代码......

http://msdn.microsoft.com/en-us/library/fx6588te%28v=vs.110%29.aspx

目前,一次连接的客户超过200个(一次可以超过1000个)。连接的客户端只是发送数据(不需要通过服务器发回消息)。

问题:Socket通常会从某些客户端收到数据(晚到1-10小时)。

在代码中应该更改哪些内容来解决问题。

我的实际代码如下......

public static ManualResetEvent allDone = new ManualResetEvent(false);

    public static void StartListening()
    {
        IPEndPoint ipEndPoint = new IPEndPoint(Dns.Resolve(Dns.GetHostName()).AddressList[0], GlobalVariable.ListenPort);
        Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {

            listener.Bind((EndPoint)ipEndPoint);
            listener.Listen(GlobalVariable.MaxConnectionBacklog);
            while (true)
            {
                allDone.Reset();
                //Console.WriteLine("Waiting for a connection...");
                listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
                allDone.WaitOne();     
            }
        }
        catch (Exception ex)
        {

        }
    }

    public static void AcceptCallback(IAsyncResult ar)
    {
        try
        {

            allDone.Set();
            Socket listener = (Socket)ar.AsyncState;
            Socket handler = ((Socket)ar.AsyncState).EndAccept(ar);

            StateObject stateObject = new StateObject();
            stateObject.workSocket = handler;


            listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);

        }
        catch (Exception ex)
        {

        }
    }

    public static void ReadCallback(IAsyncResult ar)
    {
        string content="";
        try
        {
            string str = string.Empty;
            StateObject stateObject = (StateObject)ar.AsyncState;
            Socket handler = stateObject.workSocket;


            int count = handler.EndReceive(ar);
            if (count <= 0)
                return;

            stateObject.sb.Append(Encoding.ASCII.GetString(stateObject.buffer, 0, count));

            stateObject.sb.Clear();





             if (content.IndexOf("<EOF>") > -1)
             {
               // processing data with db insertion.

             }
             else
             {
                handler.BeginReceive(stateObject.buffer, 0,stateObject.buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), stateObject);
             }

        }

        catch (Exception ex)
        {}
    }

0 个答案:

没有答案