System.ObjectDisposedException:无法访问已处置的对象。 对象名:'System.Net.Sockets.Socket'。 在System.Net.Sockets.Socket.Send(Byte []缓冲区,Int32偏移量,Int32大小,SocketFlags socketFlags,SocketError& errorCode) 在System.Net.Sockets.Socket.Send(Byte []缓冲区,Int32偏移量,Int32大小,SocketFlags socketFlags) 在System.Net.Sockets.Socket.Send(Byte [] buffer)
任何想法?
try
{
CCMSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
CCMSocket.Connect(CCMServer, CCMPort);
}
现在,在使用套接字时,catch子句捕获SocketException
,并调用重新连接方法:
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);
}
答案 0 :(得分:1)
让Connect方法创建 new 套接字并返回该套接字以发送数据。 更像是:
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);
在构建服务器应用程序时,您还应该认真考虑asynchronous socket pattern。