【问题标题】:SocketException: Address already in useSocketException:地址已在使用中
【发布时间】:2013-11-10 03:37:16
【问题描述】:

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

【问题讨论】:

  • 端口已被使用。
  • @EJP,注意:''netstat -an' 表明这最初是未使用的'
  • 糟糕,我的脚本运行了两次!我会留下问题,因为代码很好并且可以帮助某人。
  • 我收到此异常是因为我错误地假设端口已在套接字超出范围时关闭。确保正确关闭并处理套接字!

标签: .net sockets udp


【解决方案1】:

代码实际上是正确的。

脚本运行了两次。

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

【讨论】:

    猜你喜欢
    • 2018-06-07
    • 2023-01-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    相关资源
    最近更新 更多