C#套接字发送错误

时间:2015-07-20 15:01:49

标签: c#

我有这段代码

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.Sockets.Socket'。我不知道问题出在哪里,因为如果我在app load中删除套接字发送,那么关闭工作

1 个答案:

答案 0 :(得分:1)

Socket.Close最终调用.Dispose在socket上。

您在上面的评论中提到您正在运行此代码:

foreach (Socket s in samp) 
{ 
    Launcher.Send(s, Encoding.UTF8.GetBytes(GetMyIP()), 0, GetMyIP().Length, 1000); 
    s.Close(); 
}

因此,当您关闭表单时,套接字将被丢弃。