using System; using System.Net; using System.Net.Sockets; class Server { static byte[] buffer = new byte[1024]; static Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); static void Main(string[] args) { listener.Bind(new IPEndPoint(IPAddress.Any, 1234)); listener.Listen(10); Console.WriteLine("Listening on port 1234"); listener.BeginAccept(new AsyncCallback(AcceptCallback), null); Console.ReadLine(); } static void AcceptCallback(IAsyncResult ar) { Socket client = listener.EndAccept(ar); Console.WriteLine("Accepted connection from " + client.RemoteEndPoint); client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), client); listener.BeginAccept(new AsyncCallback(AcceptCallback), null); } static void ReceiveCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { Console.WriteLine("Received " + bytesRead + " bytes from " + client.RemoteEndPoint); string data = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine("Data: " + data); client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), client); } else { Console.WriteLine("Connection closed by " + client.RemoteEndPoint); client.Close(); } } }
using System; using System.Net; using System.Net.Sockets; class Client { static byte[] buffer = new byte[1024]; static Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); static void Main(string[] args) { Console.Write("Enter server IP: "); string serverIp = Console.ReadLine(); IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse(serverIp), 1234); byte[] data = System.Text.Encoding.ASCII.GetBytes("Hello, server!"); client.BeginSendTo(data, 0, data.Length, SocketFlags.None, endpoint, new AsyncCallback(SendCallback), null); Console.WriteLine("Sent message to server"); EndPoint receiveEndpoint = new IPEndPoint(IPAddress.Any, 0); client.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref receiveEndpoint, new AsyncCallback(ReceiveCallback), null); Console.ReadLine(); } static void SendCallback(IAsyncResult ar) { client.EndSendTo(ar); } static void ReceiveCallback(IAsyncResult ar) { EndPoint endpoint = new IPEndPoint(IPAddress.Any, 0); int bytesRead = client.EndReceiveFrom(ar, ref endpoint); string data = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead); Console.WriteLine("Received " + bytesRead + " bytes from server: " + data); } }This example creates a simple UDP client that sends a message to a specified server and waits for a response. It initiates an asynchronous send operation using BeginSendTo, and then begins an asynchronous receive operation using BeginReceiveFrom. When the response is received, it prints the data to the console. Package library: System.Net.Sockets