开发者

ObjectDisposeException when trying to send through a reopened socket

  1. I'm using Socket (Socket A = new Socket...) to send/receive.
  2. 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)
  3. The connect() phase checks out fine, the remote host sees the connection.
  4. 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);    
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜