0

さて、私はクライアントサーバーアプリケーションを作成していて、クライアントにメッセージをうまく送信できますが、逆に(クライアントからサーバーへ)サーバーアプリケーションを閉じると、これを修正する方法について何か助けがありますか?

public void OnDataReceived(IAsyncResult asyn)
    {
        try
        {
            SocketPacket socketData = (SocketPacket)asyn.AsyncState;

            int iRx = 0;
            iRx = socketData.m_currentSocket.EndReceive(asyn);
            char[] chars = new char[iRx + 1];
            System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
            int charLen = d.GetChars(socketData.dataBuffer,
                                     0, iRx, chars, 0);
            System.String szData = new System.String(chars);
            area1.AppendText(szData);


            WaitForData(socketData.m_currentSocket); // Continue the waiting for data on the Socket
        }
        catch (ObjectDisposedException)
        {
            System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
        }
        catch (SocketException se)
        {
            MessageBox.Show(se.Message);
        }
    }

いくつかのブレークポイントを実行した後、この部分に到達した後、textAreaに追加しようとすると、エラーなしで閉じることに気付きました。

これを修正する方法について何かアイデアはありますか?スレッドと関係があると思いますが、なぜ閉じるのかわかりません。

4

1 に答える 1

2

AppendTextが呼び出されたときに例外は発生しますか?はいの場合、コールスタックを含めることができますか?AppendTextが呼び出されたときにszDataは有効なデータですか?コードの周りにtry/catchを配置して、例外情報を取得してみてください。

try
{
    ... your code...
}
catch (Exception e)
{
    ... examine 'e' in the debugger or dump it to a log file
}

うまくいかない可能性のあることの1つは、非UIスレッドからUIコントロールにアクセスしていることですが、それは他のことである可能性があります。投稿したコードスニペットから見分けるのは難しいです。

更新:コントロールが間違ったスレッドから呼び出されているという例外があった場合は、このような関数を追加して、コントロールに直接アクセスする代わりにそれを呼び出すことができます(テストされていません):

    private void AppendText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.area1.InvokeRequired)
        {   
            SetTextCallback d = new AppendTextCallback(AppendText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.area1.AppendText(text);
        }
    }
于 2011-08-23T01:46:06.463 に答える