Simple UDP example to send and receive data from same socket

前端 未结 3 530
太阳男子
太阳男子 2020-12-12 22:10

For some reason I am having a hard time sending and receiving data from the same socket. Anyways here is my client code:

var client = new UdpClient();
IPEndP         


        
3条回答
  •  悲哀的现实
    2020-12-12 22:26

    (I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).

    In your server this line:

    var data = udpServer.Receive(ref groupEP);
    

    re-assigns groupEP from what you had to a the address you receive something on.

    This line:

    udpServer.Send(new byte[] { 1 }, 1); 
    

    Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:

    UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);
    
    while (true)
    {
        var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
        var data = udpServer.Receive(ref remoteEP);
        udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data          
    }
    

    Also if you have server and client on the same machine you should have them on different ports.

提交回复
热议问题