gpt4 book ai didi

.net - 套接字异常 : Address already in use

转载 作者:行者123 更新时间:2023-12-02 01:56:04 24 4
gpt4 key购买 nike

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

最佳答案

代码实际上是正确的。

脚本运行了两次。

只提供这个 stub 答案,这样问题就不会被误报为未答复。

关于.net - 套接字异常 : Address already in use,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19886002/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com