服務(wù)器端
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
-
- namespace UDPServer
- {
- class Program
- {
- static void Main(string[] args)
- {
- int recv;
- byte[] bytes = new byte[1024];
- IPEndPoint ip = new IPEndPoint(IPAddress.Any, 13000);
- Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- server.Bind(ip);
- Console.WriteLine("this is a UDP Server, host name is {0}", Dns.GetHostName());
- Console.WriteLine("Waiting for client");
- IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
- EndPoint Remote = (EndPoint)(sender);
- recv = server.ReceiveFrom(bytes, ref Remote);
- Console.WriteLine("Message received from {0}", Remote.ToString());
- string str = System.Text.Encoding.ASCII.GetString(bytes, 0, recv);
- Console.WriteLine("Message: {0}", str);
- str = "Hello Client!";
- bytes = System.Text.Encoding.ASCII.GetBytes(str);
- server.SendTo(bytes, Remote);
- }
- }
- }
客戶端
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Net;
- using System.Net.Sockets;
-
- namespace UDPClient
- {
- class Program
- {
- static void Main(string[] args)
- {
- int recv;
- byte[] bytes = new byte[1024];
- IPEndPoint ip = new IPEndPoint(IPAddress.Parse("10.7.19.255"), 13000);
- Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
- string str = "Hello Server!";
- bytes = System.Text.Encoding.ASCII.GetBytes(str);
- server.SendTo(bytes, ip);
- IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
- EndPoint Remote = (EndPoint)(sender);
- recv = server.ReceiveFrom(bytes, ref Remote);
- Console.WriteLine("Message received from {0}", Remote.ToString());
- str = System.Text.Encoding.ASCII.GetString(bytes, 0, recv);
- Console.WriteLine("Message: " + str);
- }
- }
- }
|