SoFunction
Updated on 2025-03-06

C# Implementing Simple Console UDP Asynchronous Communication Program Example

Implement client sending requests and server-side response mechanism

UDP client code

Copy the codeThe code is as follows:

using System;
using ;
using ;
using ;

namespace Client
{
    class Program
    {
//Client Socket Object
        private static Socket clientSocket;
//Server end point
        private static EndPoint epServer;
//Array of character that receives data
        private static byte[] receiveData;

        public static void Main(string[] args)
        {
//Instantiation of client Socket object
            clientSocket = new Socket(, , );
//Set the server IP address and corresponding port
            IPEndPoint server = new IPEndPoint(("192.168.1.165"), 11000);
//Instantiated server endpoint
            epServer = (EndPoint)server;
string msg;      // Message to be sent
byte[] sendData;     //The string to be sent
            while (true) {
msg = ();   //Enter the message to be sent
if (msg == "exit") break;   // When entering "exit", exit the client program
//Convert the message to a character array through ASCII encoding,
//If you want to send Chinese characters or other special symbols, you can use UTF-8
                sendData = (msg);   
//Start asynchronous sending of messages
//Parameters: sendData
//Parameters: 0: The starting position of data to be sent
//Parameters:: Number of bytes to send data
//Parameters:: bitwise combination method
//Parameters: epServer: Receiver device (including IP and port)
//Parameters: new AsyncCallback(SendData):   Delegate
//Parameters: null:
                (sendData, 0, , ,
                    epServer, new AsyncCallback(SendData), null);
//Instantiate the character array that receives data
//If it has been initialized at the time of declaration, it still needs to be re-initialized here
//When the last received data length is greater than this time, the array contains the remaining data received last time
//For example: Last time I received "You little funny guy". This time, I received "joking".
//The data in the array is: "Kidding funny".
                receiveData = new byte[1024];
//Start asynchronous reception of messages
//The parameter part corresponds to the asynchronous sending part, which is basically the same
                (receiveData, 0, , ,
                    ref epServer, new AsyncCallback(ReceiveData), null);
            }
        }

//Delegate function for sending messages asynchronously
        private static void SendData(IAsyncResult iar)
        {
//Complete asynchronous sending
            (iar);
        }

//Delegate function for asynchronously receiving messages
        private static void ReceiveData(IAsyncResult iar)
        {
//Complete asynchronous reception. recv represents the number of bytes received.
            int recv = (iar);
//Print out the received data
            ("Server: " + (receiveData, 0, recv));
        }

    }
}

UDP server side code

Copy the codeThe code is as follows:

using System;
using ;
using ;
using ;

namespace Server
{
    class AsyncUdpServer
    {
//Server side Socket object
        private static Socket serverSocket;
//Array of character that receives data
        private static byte[] receiveData = new byte[1024];

        public static void Main(string[] args)
        {
//Instantiate the server-side Socket object
            serverSocket = new Socket(, , );
//The IP and port on the server side are actually: 0.0.0.0, which means any, basically means the native IP
            IPEndPoint server = new IPEndPoint(, 11000);
//The Socket object is bound to the IP and port of the server side
            (server);
//The IP and port of the client, port 0 means any port
            IPEndPoint clients = new IPEndPoint(, 0);
//Instantiated client endpoint
            EndPoint epSender = (EndPoint)clients;
//Start asynchronous reception of messages. After receiving, epSender stores the sender's IP and port
            (receiveData, 0, , ,
                ref epSender, new AsyncCallback(ReceiveData), epSender);
            ("Listening...");
            ();
        }

        private static void SendData(IAsyncResult iar)
        {
            (iar);
        }

        private static void ReceiveData(IAsyncResult iar)
        {
//The IP and port of the client, port 0 means any port
            IPEndPoint client = new IPEndPoint(, 0);
//Instantiated client endpoint
            EndPoint epSender = (EndPoint)client;
//End asynchronous reception of messages recv represents the number of characters received
            int recv = (iar, ref epSender);           
//Print out the received data, what encoding method is used by the sender, and what encoding method is used here to convert it into a string
            ("Client:" + (receiveData, 0, recv));
//Define the message to be sent back to the client, adopt ASCII encoding,
//If you want to send Chinese characters or other special symbols, you can use UTF-8
            byte[] sendData = ("hello");
//Start asynchronous sending messages. epSender is the client IP and port information when the message was last received.
            (sendData, 0, , ,
                epSender, new AsyncCallback(SendData), epSender);
//Reinstand the received data byte array
            receiveData = new byte[1024];
//Start asynchronously receiving messages. The delegate function here is this function itself, recursively
            (receiveData, 0, , ,
                ref epSender, new AsyncCallback(ReceiveData), epSender);
        }

    }
}