问题
- I'm using Socket (Socket A = new Socket...) to send/receive.
- when something bed happens (disconnection), I'm trying to close/dispose old object, and then instancing a new socket (A = new Socket...) (same host/port)
- The connect() phase checks out fine, the remote host sees the connection.
- Upon trying to send the very first byte, I immediately get:
System.ObjectDisposedException: Cannot access a disposed object. Object name: 'System.Net.Sockets.Socket'. at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, SocketError& errorCode) at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags) at System.Net.Sockets.Socket.Send(Byte[] buffer)
Any Ideas?
try
{
CCMSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
CCMSocket.Connect(CCMServer, CCMPort);
}
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);
}
回答1:
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
}
and
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.
来源:https://stackoverflow.com/questions/4704477/objectdisposeexception-when-trying-to-send-thru-a-reopened-socket