1

こんにちは、以下のサンプル コードを使用して C# Winforms アプリケーションに取り組んでいます。

https://msdn.microsoft.com/en-us/library/bbx2eya8(v=vs.110).aspx

正しい IP アドレスとポート番号に接続しますが、文字列コマンドを送信して応答を待った後、ReceiveCallback が実行されていないためにアプリケーションが停止し、receiveDone ManualResetEvent が設定されません。100% 確実に応答が返ってくると思いますが、代わりにアプリケーションがスタックして ReceiveCallback メソッドを実行しません。ReceiveCallback メソッドが実行されない理由は何でしょうか?

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, 0,
                new AsyncCallback(ReceiveCallback), state);
        }
        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);

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

コンテキスト: アプリケーションは、DC 電気トルク ツール コントローラーのインターフェイスです。コントローラーの IP アドレスとポート 4545 に接続し、Open Protocol コマンドを送信して設定を変更できます。

4

2 に答える 2