【问题标题】:Concurrent send and receive data in one port with udpclient使用udpclient在一个端口并发发送和接收数据
【发布时间】:2012-01-08 23:51:05
【问题描述】:

我正在尝试使用本地端口 50177 向特定端点发送和接收数据。发送数据非常好,但是当程序尝试接收数据时它无法接收任何数据。当我用 Wireshark 嗅探网络时,我看到服务器向我发送了数据。我知道我不能在一个端口上同时拥有 2 个 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);

【问题讨论】:

    标签: c# udp


    【解决方案1】:

    您绝对可以在一个端口上拥有两个 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);
    }
    

    【讨论】:

    • 应该sendClient.Client.Bind(ep1);sendClient.Client.Bind(ep2);
    • @AlexJohnson 不,ep1 是正确的。这是关于将两个 UdpClient 绑定到一个端口。
    • @Farzan,但是当你将多个套接字绑定到同一个端点,并且只使用一个来接收时,你不会开始丢失传入的数据吗?数据会只出现在第一个创建的套接字的输入缓冲区中,还是全部出现?
    • 这很有帮助。但是,我发现如果我在绑定接收器之前将发送器绑定到端点,它就不起作用了。首先绑定接收器确实有效,就像在这个例子中一样。
    • 为了扩展我上面的评论,我的意思是我必须在将发送客户端绑定到端点之前调用 receiveClient.Receive(ref ep1)。
    【解决方案2】:

    使用与发送相同的 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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多