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
}

可能出错的一件事是您正在从非 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 回答