Search code examples
c#serverudpsendto

(Socket.SendTo) How do I response/send back data to the client that my server began receive? C#


I'm doing an UDP server, I can receive data fine but I don't know how to store the endpoint to send data back.

The commentary at the ultimate line of SetupServer() is where i dont know how to get the EndPoint.

This is my server code:

static private byte[] buffer = new byte[1024];
    static private Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    private const int port = 904;

    static void Main(string[] args) {
        SetupServer();
        Console.ReadLine();
    }
    static private void SetupServer() {
        Console.WriteLine($"{DateTime.Now}: Setting up server on {port}...");
        EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
        serverSocket.Bind(remoteEP);
        Console.WriteLine($"{DateTime.Now}: Server created successfully");
        serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP,BeginReceive, null);
        //serverSocket.SendTo(buffer, 0, buffer.Length, SocketFlags.None, remoteEP);
    }
    static private void BeginReceive(IAsyncResult ar) {
        int recv = serverSocket.EndReceive(ar);
        byte[] dataBuf = new byte[recv];
        Array.Copy(buffer, dataBuf, recv);
        Console.WriteLine($"{DateTime.Now}: {Encoding.ASCII.GetString(dataBuf)}");

        EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
        serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP, BeginReceive, null);
    }

Solution

  • I figure out how to do it. I replaced the serverSocket.EndReceive(ar) in the BeginReceive method to EndReceiveFrom(ar,ref epSender) and with that end point (epSender) i can call the BeginReceiveFrom method.

        static private void SetupServer() {
        Console.WriteLine($"{DateTime.Now}: Setting up server on {port}...");
        EndPoint remoteEP = new IPEndPoint(IPAddress.Any, port);
        serverSocket.Bind(remoteEP);
        Console.WriteLine($"{DateTime.Now}: Server created successfully");
        serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP,BeginReceive, serverSocket);
    }
    static private void BeginReceive(IAsyncResult ar) {
        EndPoint epSender = new IPEndPoint(IPAddress.Any, port);
        int recv = serverSocket.EndReceiveFrom(ar,epSender);
        byte[] dataBuf = new byte[recv];
        Array.Copy(buffer, dataBuf, recv);
        Console.WriteLine($"{DateTime.Now}: {Encoding.ASCII.GetString(dataBuf)}");
    
        serverSocket.SendTo(dataBuf,epSender)
    
        serverSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP, BeginReceive, serverSocket);
    }