3
我試圖通過異步套接字監聽趕上傳入UDP數據包SocketException:地址已在使用
(我也一直在經歷一個非常讀很好的教程在這裏: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
@EJP,注意:''netstat -an'顯示這個文件最初未被使用' –
我的不好,我的腳本運行了兩次!我會留下問題,因爲代碼很好,可以幫助某人。 –