本文介绍了尝试通过重新打开的套接字发送ObjectDisposeException时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
- 我正在使用Socket(Socket A = new Socket ...)发送/接收.
- 当床上发生某些事情(断开连接)时,我试图关闭/放置旧对象,然后实例化一个新的套接字(A = new Socket ...)(相同的主机/端口)
- connect()阶段检查正常,远程主机可以看到连接.
- 尝试发送第一个字节时,我立即得到:
有什么想法吗?
try
{
CCMSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
CCMSocket.Connect(CCMServer, CCMPort);
}
现在,使用套接字时,catch子句捕获SocketException
,并调用reconnect方法:
Now, when working with the socket, the catch clause catches SocketException
, and calls the reconnect method:
try
{
//Verify the the socket is actually disconnected
byte[] Empty = new byte[0];
CCMSocket.Send(Empty);
}
catch (Exception ex)
{
bool connected = false;
int reconnectCounter = 0;
do
{
reconnectCounter++;
Disconnect(); //<-- Just CCMSocket.Disconnect(true) in a try/catch
if (Connect(CCMServer, CCMPort)) // <-- method given above
{
connected = true;
CCMSocket.Send(LoginData); // this fails
}
} while (!connected);
}
推荐答案
让您的Connect方法创建一个 new 套接字并返回该套接字以发送数据.更像是:
Have your Connect method create a new socket and return that socket to send data.Something more like:
try
{
CCMSocket = new Socket();
CCMSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
CCMSocket.Connect(CCMServer, CCMPort);
return CCMSocket
}
和
do
{
reconnectCounter++;
Disconnect(); //<-- Just CCMSocket.Disconnect(true) in a try/catch
var newSocket = Connect(CCMServer, CCMPort); // <-- method given above
if (newSocket != null)
{
connected = true;
newSocket.Send(LoginData); // should work
CCMSocket = newSocket; // To make sure existing references work
}
} while (!connected);
在构建服务器时,您还应该认真考虑异步套接字模式应用程序.
You should also seriously consider the asynchronous socket pattern when building server applications.
这篇关于尝试通过重新打开的套接字发送ObjectDisposeException时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!