簡體   English   中英

無法使用異步服務器套接字處理多個消息

[英]Unable to process multiple messages with async server socket

我有一個異步服務器套接字(基於此處找到的MSDN示例),適合1條消息。 我目前正在接收39字節的數據,這是第一條消息,並且效果很好。 但是服務器套接字無法接收消息2和3。這是我的代碼

private void PrivateStartListening()
    {
        try
        {
            var socket = ManagementSocket.Socket;
            var localEndPoint = ManagementSocket.GetEndPoint();
            socket.Bind(localEndPoint);
            socket.Listen(100);
            Msg.Debug("Listening...");
            while (true)
            {
                // Set the event to nonsignaled state.  
                AllDone.Reset();

                socket.BeginAccept(
                    AcceptCallback,
                    socket);

                // Wait until a connection is made before continuing.  
                AllDone.WaitOne();
            }

        }
        catch (Exception e)
        {
            Msg.Debug(e.ToString());
        }

        Msg.Debug("read completed");

    }

    private void AcceptCallback(IAsyncResult Ar)
    {
        // Signal the main thread to continue.  
        AllDone.Set();

        // Get the socket that handles the client request.  
        var listener = (Socket)Ar.AsyncState;
        var handler = listener.EndAccept(Ar);

        // Create the state object.  
        var state = new StateObject { WorkSocket = handler };
        handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0,
            ReadCallback, state);

    }

    private void ReadCallback(IAsyncResult Ar)
    {
        // Retrieve the state object and the handler socket  
        // from the asynchronous state object.  
        var state = (StateObject)Ar.AsyncState;
        var handler = state.WorkSocket;

        // Read data from the client socket.   
        var bytesRead = handler.EndReceive(Ar);

        if (bytesRead > 0)
        {
            handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0,
                ReadCallback, state);
        }

        // There  might be more data, so store the data received so far.  
        state.Sb.Append(Encoding.ASCII.GetString(
            state.Buffer, 0, bytesRead));

        // Check for end-of-file tag. If it is not there, read   
        // more data.  
        var content = state.Sb.ToString();

        // All the data has been read from the   
        // client. Display it on the console.  
        Msg.Debug($"Read {content.Length} bytes from socket. \n Data : {content}");
        var fields = content.TrimEnd('\r', '\n').Split(',').ToList();
        if (fields[1] == "0")
        {
            handler.BeginReceive(state.Buffer, 0, StateObject.BUFFER_SIZE, 0,
                ReadCallback, state);
        }
        var paymentDetails = ProcessPaymentResponse(fields);
        if (paymentDetails != null)
        {
            ResponseQueue.Enqueue(paymentDetails);
            ResponseResetSignal.Set();
        }

        // Echo the data back to the client.  
        //Send(handler, content);

    }


    private static void Send(Socket Handler, string Data)
    {
        // Convert the string data to byte data using ASCII encoding.  
        var byteData = Encoding.ASCII.GetBytes(Data);

        // Begin sending the data to the remote device.  
        Handler.BeginSend(byteData, 0, byteData.Length, 0,
            SendCallback, Handler);
    }

    private static void SendCallback(IAsyncResult Ar)
    {
        try
        {
            // Retrieve the socket from the state object.  
            var handler = (Socket)Ar.AsyncState;

            // Complete sending the data to the remote device.  
            var bytesSent = handler.EndSend(Ar);
            Msg.Debug($"Sent {bytesSent} bytes to client.");

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }`

我還附上了wireshark看到的屏幕截圖(因此肯定會發送多個消息) Wireshark接收到的消息,但不是asny服務器套接字的消息

我的問題是,我怎么能成功接收到第一條消息,但不能立即收到/

我整個上午都在仔細閱讀檔案,但我仍然不明智。 如果確實還有重復的問題,我也表示歉意。 以前的答案都沒有對我有用。 任何幫助或提示將不勝感激。

您的ReadCallback()僅讀取可用數據的第一部分,然后退出。 因此,跳入ReadCallback()的唯一方法是建立另一個連接:偵聽器-> AcceptCallback-> ReadCallback

因此,只需嘗試將ReadCallback修改為基於循環的版本,它會等待新數據,直到套接字被交易方關閉(或者觸發了停止循環的另一個事件,可以由用戶決定)為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM