服务器应用程序在收到消息时关闭
好吧,我正在制作一个客户端-服务器应用程序,我可以很好地向客户端发送消息,但是当我以相反的方式(客户端到服务器)执行此操作时,服务器应用程序就会关闭,有关如何解决此问题的任何帮助吗?
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 时,它会关闭而不会出现错误。
关于如何解决这个问题有什么想法吗?我猜测与线程有关,但不确定为什么它会关闭。
Well I'm making a Client-Server application and I can send messages to my client just fine but when I do it the other way around (Client to server) the server application just closes down, any help on how to fix this?
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);
}
}
After doing some breakpoints I realized it closes after reaching this part when it tries to append it on the textArea it closes without an error.
Any ideas on how to fix this? I guessing something to do with the threads but not sure why it just closes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
调用
AppendText
时是否发生异常?如果是的话,你能包括调用堆栈吗?调用 AppendText 时 szData 数据是否有效?尝试在代码中添加 try/catch 以获取异常信息:可能出现问题的一件事是您正在从非 UI 线程访问 UI 控件,但也可能是其他原因。从您发布的代码片段中很难看出。
更新:
如果异常是从错误的线程调用控件,您可以尝试添加这样的函数,然后调用它,而不是直接访问控件(未经测试):
Does an exception happen when
AppendText
is called? If yes, can you include the call stack? Is szData valid data when AppendText is called? Try putting a try/catch around the code to get the exception information:One thing that might be going wrong is that you are accessing a UI control from the non-UI thread, but it could be other things. It's hard to tell from the code snippet you posted.
Updated:
If the exception was that the control is being invoked from the wrong thread, you can try adding a function like this, then calling that instead of accessing the control directly (untested):