SocketException:地址已在使用中

时间:2013-11-10 03:37:17

标签: .net sockets udp

我试图通过异步套接字侦听器

捕获传入的UDP数据包

我正在使用此处的代码:http://www.alexthissen.nl/blogs/main/archive/2004/12/26/receiving-udp-messages-using-udpclient-or-socket-classes.aspx

(我也在这里阅读了一篇非常好的教程:http://www.winsocketdotnetworkprogramming.com/clientserversocketnetworkcommunication8d.html与问题无关,只是把它作为一个好资源加入)

但是,我收到以下错误:

SocketException: Address already in use

以下是代码:

private Byte[] buffer;

public void StartListening()
{
    int port = 6500; // 'netstat -an' shows this is initially unused
    int bufferSize = 1024;
    buffer = new Byte[bufferSize];
    IPAddress ip = IPAddress.Any; // IPAddress.Parse( "127.0.0.1" );
    IPEndPoint ep = new IPEndPoint(ip, port);
    Socket sock = new Socket(ip.AddressFamily, SocketType.Dgram, ProtocolType.Udp);

    sock.Bind(ep); // 'SocketException: Address already in use'

    sock.BeginReceive(buffer, 0, 1024, SocketFlags.None, new AsyncCallback(this.OnReceive), sock);
}

private void OnReceive(IAsyncResult ar)
{
    Socket s1 = (Socket)ar.AsyncState;
    int x = s1.EndReceive(ar);
    string message = System.Text.Encoding.ASCII.GetString(buffer, 0, x);
    Console.WriteLine(message);
    s1.BeginReceive(buffer, 0, 1024, SocketFlags.None, new AsyncCallback(this.OnReceive), s1);
}   

1 个答案:

答案 0 :(得分:0)

代码实际上是正确的。

脚本运行了两次。

只提供这个存根答案,这样问题就不会错误地记录为未答复。