Write a UPD today
1. Server:
Code
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Net. Sockets;
Using System. Net;
Namespace ConsoleApplication1
{
Class Program
{
Static void Main (string [] args)
{
// 1. Create a set of characters
Socket socket = new Socket (AddressFamily. InterNetwork, SocketType. Dgram, ProtocolType. Udp );
// 2. Fill in the IP address
IPEndPoint ipe = new IPEndPoint (IPAddress. Any, 4321 );
// 3. Bind
Socket. Bind (ipe );
// Wait for the client to connect
Console. WriteLine ("This is a Server, host name is {0}", Dns. GetHostName ());
Console. WriteLine ("Waiting for a client ...");
// 4. Obtain the Client IP Address
IPEndPoint sender = new IPEndPoint (IPAddress. Any, 0 );
EndPoint remote = (EndPoint) sender;
// 5. Receive client data
Byte [] buffer = new byte [1024];
Socket. ReceiveFrom (buffer, ref remote );
Console. WriteLine (remote. ToString ());
Console. WriteLine (Encoding. Unicode. GetString (buffer ));
Console. ReadKey ();
}
}
}
2. Client
Code
// 1. Create a set of characters
M_s = new Socket (AddressFamily. InterNetwork, SocketType. Dgram, ProtocolType. Udp );
// 2. Enter the Server IP Address
IPAddress ip = IPAddress. Parse ("127.0.0.1 ");
IPEndPoint ipe = new IPEndPoint (ip, 4321 );
String welcome = "Hello ...";
Byte [] data = new byte [1024];
Data = Encoding. Unicode. GetBytes (welcome );
// 3. Send data
M_s.SendTo (data, data. Length, SocketFlags. None, ipe );
Console. ReadKey ();
3. Results