尝试通过重新打开的套接字发送时出现ObjectDisposeException

时间:2011-01-16 08:36:33

标签: c# sockets objectdisposedexception

  1. 我正在使用Socket(Socket A = new Socket ...)发送/接收。
  2. 当床上发生事情(断开连接)时,我试图关闭/处置旧对象,然后实例化新套接字(A =新套接字......)(相同主机/端口)
  3. connect()阶段检出正常,远程主机看到连接。
  4. 在尝试发送第一个字节时,我立即得到:
  5.   

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

1 个答案:

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