我有2個程序,1個用於發送UDP廣播消息,1個正在監聽此廣播。我的問題是,有時當我發送廣播時,接收器會收到2條消息。爲什麼?發送UDP廣播,接收多條消息
接收器代碼:
public class Receiver {
private readonly UdpClient udp = new UdpClient(15000);
private void StartListening()
{
this.udp.BeginReceive(Receive, new object());
}
private void Receive(IAsyncResult ar)
{
IPEndPoint ip = new IPEndPoint(IPAddress.Any, 15000);
byte[] bytes = udp.EndReceive(ar, ref ip);
string message = Encoding.ASCII.GetString(bytes);
StartListening();
}
}
發件人代碼:
public class Sender {
public void Send() {
UdpClient client = new UdpClient();
IPEndPoint ip = new IPEndPoint(IPAddress.Broadcast, 15000);
byte[] bytes = Encoding.ASCII.GetBytes("Foo");
client.Send(bytes, bytes.Length, ip);
client.Close();
}
}
嗨。我想用你的代碼來傳輸UDP文件。但我不知道如何處理接收部分!應該如何實施?它將如何開始從網絡中獲取內容? – Shamim
@Shamim,網上有很多資源,有點Google搜索應該有所幫助。查找服務器/客戶端示例。 –
'IPEndPoint ip = new IPEndPoint(IPAddress.Any,15000);'只能是'IPEndPoint ip = null;' - 它不是結構體。它在'EndReceive()'方法中的用途是定義發送者。用任何東西填充它都有點誤導。 – maxp