c socket programming udp client code sharing

  • 2020-05-26 10:02:41
  • OfStack


Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());
// Set the server endpoint 
IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8001);
// Creates a socket to connect to the server, specifying the network type, data connection type, and network protocol 
Socket ConnSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Client Message:Hello!!!";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(welcome);
// Send a test message to the server 
ConnSocket.SendTo(data, data.Length, SocketFlags.None, ipe);
IPEndPoint server = new IPEndPoint(IPAddress.Any, 0);
// Server endpoint 
EndPoint Remote = (EndPoint)server;
data = new byte[1024];
// For something that doesn't exist IP Address, which can be unblocked for a specified period of time by adding this line of code 
//server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100);
int recv = ConnSocket.ReceiveFrom(data, ref Remote);
// Print the information sent back from the server 
Console.WriteLine("Message received from {0}: ", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
while (true) // Messages can be sent to the server in real time 
{
    string input = Console.ReadLine();
    if (input == "exit") // disconnect 
    {
        ConnSocket.SendTo(Encoding.ASCII.GetBytes(input), Remote);
        data = new byte[1024];
        recv = ConnSocket.ReceiveFrom(data, ref Remote);
        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
        break;
    }
    else
    {
        ConnSocket.SendTo(Encoding.ASCII.GetBytes("Client Message:" + input), Remote);
        data = new byte[1024];
        recv = ConnSocket.ReceiveFrom(data, ref Remote);
        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
    }
}
Console.WriteLine("Stopping Client.");
ConnSocket.Close();

Related articles: