尝试通过重新打开的套接字发送时出现 ObjectDisposeException
- 我使用 Socket (
Socket A = new Socket...
) 来发送/接收。 - 当发生某些事情(断开连接)时,我尝试关闭/处置旧对象,然后实例化一个新套接字(
A = new Socket...
)(同一主机/端口 - ) >connect() 阶段检查正常,远程主机看到连接。
- 在尝试发送第一个字节时,我立即得到:
System.ObjectDisposeException:无法访问已处置的对象。 对象名称:“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[] 缓冲区)
有什么想法吗?
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);
}
- 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);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让您的 Connect 方法创建一个新套接字并返回该套接字以发送数据。
更像是:
当
您使用异步套接字模式时构建服务器应用程序。
Have your Connect method create a new socket and return that socket to send data.
Something more like:
and
You should also seriously consider the asynchronous socket pattern when building server applications.