接收消息时服务器应用程序关闭

时间:2011-08-23 01:33:46

标签: c# sockets asyncsocket

我正在制作一个客户端 - 服务器应用程序,我可以向我的客户端发送消息就好了但是当我这样做时(客户端到服务器)服务器应用程序只是关闭,任何有关如何修复的帮助此?

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时它会关闭而没有错误。

有关如何解决此问题的任何想法?我猜测与线程有关,但不确定为什么它会关闭。

1 个答案:

答案 0 :(得分: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);
        }
    }