c# socket发送错误
本文关键字:错误 socket | 更新日期: 2023-09-27 18:03:30
我有这样的代码
public static void Send(Socket socket, byte[] buffer, int offset, int size, int timeout)
{
int startTickCount = Environment.TickCount;
int sent = 0; // how many bytes is already sent
do
{
if (Environment.TickCount > startTickCount + timeout)
throw new Exception("Timeout.");
try
{
sent += socket.Send(buffer, offset + sent, size - sent, SocketFlags.None);
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.WouldBlock ||
ex.SocketErrorCode == SocketError.IOPending ||
ex.SocketErrorCode == SocketError.NoBufferSpaceAvailable)
{
// socket buffer is probably full, wait and try again
Thread.Sleep(30);
}
else
throw ex; // any serious error occurr
}
} while (sent < size);
}
在表单打开和关闭时发送它:
打开时:
Launcher.Send(sock, Encoding.UTF8.GetBytes("Hello world"), 0, "Hello World".Length, 1000);
它工作得很好,但是在窗体关闭时:
try
{
Launcher.Send(s, Encoding.UTF8.GetBytes("Bye world"), 0, "Bye world".Length, 1000);
}
catch
{
Message.Error("Error");
}
我总是得到错误信息。怎么了?提前感谢
编辑:我删除了try{}catch{}。现在我得到:不能访问一个处置的对象。对象名称:' system.net.socket.socket '。我不知道问题在哪里,因为如果我在app load中删除socket send,那么关闭工作
插座。Close结束时调用套接字上的. dispose。
您在上面的评论中提到,您正在运行以下代码:
foreach (Socket s in samp)
{
Launcher.Send(s, Encoding.UTF8.GetBytes(GetMyIP()), 0, GetMyIP().Length, 1000);
s.Close();
}
因此,当您关闭表单时,套接字已被处理。