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.創(chuàng)建套節(jié)字 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // 2.填充IP IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 4321); // 3.綁定 socket.Bind(ipe); // 等待客戶機(jī)連接 Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName()); Console.WriteLine("Waiting for a client..."); // 4.得客戶機(jī)IP IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint remote = (EndPoint)sender; // 5.接收客戶機(jī)數(shù)據(jù) byte[] buffer = new byte[1024]; socket.ReceiveFrom(buffer, ref remote); Console.WriteLine(remote.ToString()); Console.WriteLine(Encoding.Unicode.GetString(buffer)); Console.ReadKey(); } } } |
|