ObjectDisposeException when trying to send thru a reopened socket

浪子不回头ぞ 提交于 2020-01-06 09:57:25

问题


  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);    
}

回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!