C # socket programming for udp clients
This article mainly introduces c # socket programming for udp clients.
The Code is as follows:
Console. WriteLine ("This is a Client, host name is {0}", Dns. GetHostName ());
// Set the server end point
IPEndPoint ipe = new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 8001 );
// Create a socket connected to the server, specify 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 );
// End point of the server
EndPoint Remote = (EndPoint) server;
Data = new byte [2, 1024];
// For IP addresses that do not exist, you can remove the blocking mode limit within the specified time after 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 ed 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 [2, 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 [2, 1024];
Recv = ConnSocket. ReceiveFrom (data, ref Remote );
Console. WriteLine (Encoding. ASCII. GetString (data, 0, recv ));
}
}
Console. WriteLine ("Stopping Client .");
ConnSocket. Close ();