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

System.ObjectDisposedException:无法访问已处置的对象。对象名称:“System.Net.Sockets.Socket”。在 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, System.Net.Sockets.Socket.Send(Byte[] 缓冲区) 处的 SocketFlags socketFlags)

有任何想法吗?

try
{
   CCMSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
   CCMSocket.Connect(CCMServer, CCMPort);
}

现在,当使用套接字时,catch 子句会捕获SocketException并调用 reconnect 方法:

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

1 回答 1

1

让您的 Connect 方法创建一个套接字并返回该套接字以发送数据。更像是:

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

在构建服务器应用程序时,您还应该认真考虑异步套接字模式。

于 2011-01-16T10:18:22.520 回答