4

我正在尝试通过异步套接字侦听器捕获传入的 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);
}   
4

1 回答 1

2

代码实际上是正确的。

该脚本运行了两次。

只需提供这个存根答案,这样问题就不会被误认为未回答。

于 2016-02-19T15:09:41.960 回答