簡體   English   中英

異步客戶端套接字不接收數據

[英]Asynchronous client socket not receiving data

我嘗試使用異步套接字通信實現我的應用程序。 它完美地連接並發送請求但我沒有從服務器(Java服務器)接收任何數據。 套接字連接是

client.BeginConnect(hostname, port,
            new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();

  private static void ConnectCallback(IAsyncResult ar) {
    try {
        // Retrieve the socket from the state object.
        Socket client = (Socket) ar.AsyncState;

        // Complete the connection.
        client.EndConnect(ar);

        Console.WriteLine("Socket connected to {0}",
            client.RemoteEndPoint.ToString());

        // Signal that the connection has been made.
        connectDone.Set();
    } catch (Exception e) {
        Console.WriteLine(e.ToString());
    }
}

private static void Receive(Socket client)
{
    try
    {
        // Create the state object.
        StateObject state = new StateObject();
        state.workSocket = client;

        // Begin receiving the data from the remote device.
        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None,
            new AsyncCallback(ReceiveCallback), client);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

private static void ReceiveCallback(IAsyncResult ar)
{
    try
    {
        // Retrieve the state object and the client socket 
        // from the asynchronous state object.
        StateObject state = (StateObject)ar.AsyncState;
        Socket client = state.workSocket;

        // Read data from the remote device.
        int bytesRead = client.EndReceive(ar);
        Console.WriteLine(response);
        if (bytesRead > 0)
        {
            // There might be more data, so store the data received so far.
            state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

            // Get the rest of the data.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        else
        {
            // All the data has arrived; put it in response.
            if (state.sb.Length > 1)
            {
                response = state.sb.ToString();
            }
            // Signal that all bytes have been received.
            receiveDone.Set();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

任何幫助,將不勝感激。

你的代碼幾乎沒問題,有一個嚴重的錯誤。 在BeginReceive中,您將客戶端套接字實例作為狀態對象。 在ReceiveCallback函數中,您將其強制轉換為StateObject而不是套接字。 這將導致在控制台上顯示異常。

盡管如此,還有這個錯誤,將觸發ReceiveCallback函數開頭的斷點。 你試過這個嗎? 無論如何都應該拋出異常。

如果斷點未觸發,則應獨立檢查是否確實從服務器發送了某些內容。 當然,正如你所說的那樣,假設連接有效。

暫無
暫無

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

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