SoFunction
Updated on 2025-03-07

C# socket programming udp client implementation code sharing


("This is a Client, host name is {0}", ());
//Set the server endpoint
IPEndPoint ipe = new IPEndPoint(("127.0.0.1"), 8001);
//Create sockets to connect to the server, specify network type, data connection type and network protocol
Socket ConnSocket = new Socket(, , );
string welcome = "Client Message:Hello!!!";
byte[] data = new byte[1024];
data = (welcome);
//Send test messages to the server
(data, , , ipe);
IPEndPoint server = new IPEndPoint(, 0);
//Server endpoint
EndPoint Remote = (EndPoint)server;
data = new byte[1024];
//For non-existent IP addresses, after adding this line of code, the blocking mode limit can be unblocked within a specified time
//(, , 100);
int recv = (data, ref Remote);
//Print the message sent back from the server
("Message received from {0}: ", ());
((data, 0, recv));
While (true) //You can send messages to the server in real time
{
    string input = ();
if (input == "exit") //Disconnection
    {
        ((input), Remote);
        data = new byte[1024];
        recv = (data, ref Remote);
        ((data, 0, recv));
        break;
    }
    else
    {
        (("Client Message:" + input), Remote);
        data = new byte[1024];
        recv = (data, ref Remote);
        ((data, 0, recv));
    }
}
("Stopping Client.");
();