2011-11-29 160 views
2

我試圖發送和接收數據到本地端口50177的特定端點。發送數據確實很好,但是當程序試圖接收數據時它不能接收任何。當我用Wireshark嗅探網絡時,我發現服務器向我發送了數據。我知道我不能同時在一個端口上安裝2個UdpClient。併發發送和接收數據在一個端口與udpclient

任何人都可以幫助我嗎?

UdpClient udpClient2 = new UdpClient(50177); 
IPEndPoint Ip2 = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1005); 
udpClient2.Send(peerto255, peerto255.Length, Ip2); 

IPEndPoint Ip = new IPEndPoint(IPAddress.Parse("10.10.240.1"), 1005); 
var dgram = udpClient2.Receive(ref Ip); 

回答

1

使用相同的IPEndPoint接收您用於發送的IPEndPoint。

UdpClient udpClient2 = new UdpClient(50177); 
IPEndPoint Ip2 = new IPEndPoint(IPAddress.Parse("255.255.255.255"), 1005); 
udpClient2.Send(peerto255, peerto255.Length, Ip2); 
var dgram = udpClient2.Receive(ref Ip2); 
4

您可以在一個端口上確實擁有兩個UdpClient,但在綁定到端點之前需要設置套接字選項。

private static void SendAndReceive() 
{ 
    IPEndPoint ep1 = new IPEndPoint(IPAddress.Any, 1234); 
    ThreadPool.QueueUserWorkItem(delegate 
    { 
    UdpClient receiveClient = new UdpClient(); 
    receiveClient.ExclusiveAddressUse = false; 
    receiveClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); 
    receiveClient.Client.Bind(ep1); 
    byte[] buffer = receiveClient.Receive(ref ep1); 
    }); 

    UdpClient sendClient = new UdpClient(); 
    sendClient.ExclusiveAddressUse = false; 
    sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); 
    IPEndPoint ep2 = new IPEndPoint(IPAddress.Parse("X.Y.Z.W"), 1234); 
    sendClient.Client.Bind(ep1); 
    sendClient.Send(new byte[] { ... }, sizeOfBuffer, ep2); 
} 
相關問題