我正在尝试通过异步套接字侦听器捕获传入的 UDP 数据包
(我也在这里阅读了一个非常好的教程: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);
}