标签:
使用UdpClient类进行编程
UdpClient类的使用方法
第一阶段 创建UdpClient实例
1 UdpClient udpClient = new UdpClient(); 2 IPAddress remoteAddress = IPAddress.Parse("127.0.0.1"); 3 IPEndPoint iep = new IPEndPoint(remoteAddress, 8000);
第二阶段 数据发送
1 byte[] sendBytes = System.Text.Encoding.Unicode.GetBytes("Hello C#"); 2 udpClient.Send(sendBytes,sendBytes.Length,iep);
第二阶段 数据接收
1 IPEndPoint iep2 = new IPEndPoint(IPAddress.Any, 0); 2 byte[] receiveBytes = udpClient.Receive(ref iep2); 3 string getData = System.Text.Encoding.Unicode.GetString(receiveBytes);
第三阶段 连接关闭
1 udpClient.Close();
一般常用声明的方式如下
1 UdpClient udpClient2 = new UdpClient("127.0.0.1",8000);
2 udpClient2.Send(sendBytes, sendBytes.Length);
测试代码:
服务器程序:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 StartListener(); 6 Console.ReadLine(); 7 } 8 9 private static void StartListener() 10 { 11 UdpClient udpServer = new UdpClient(8000); //服务器方的端口号为8000 12 13 IPEndPoint myHost = null; 14 15 try 16 { 17 while(true) 18 { 19 Console.WriteLine("等待接收..."); 20 byte[] getBytes = udpServer.Receive(ref myHost); 21 string getString = Encoding.Unicode.GetString(getBytes, 0, getBytes.Length); 22 Console.WriteLine("接收信息:{0}",getString); 23 if (getString == "quit") 24 break; 25 26 //向客户端回送消息 27 string sendString = "你好,Client"; 28 Console.WriteLine("发送消息:{0}", sendString); 29 byte[] sendBytes = Encoding.Unicode.GetBytes(sendString); 30 udpServer.Send(sendBytes, sendBytes.Length, "127.0.0.1", 8001); 31 32 } 33 34 udpServer.Close(); 35 Console.WriteLine("Client已经退出,请按回车键退出"); 36 37 } 38 catch(Exception e) 39 { 40 Console.WriteLine(e.Message); 41 } 42 43 } 44 }
客户端程序:
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 string sendString = "客户端发送"; 6 Send(sendString); 7 Send("quit"); 8 Console.WriteLine(); 9 } 10 11 private static void Send(string sendString) 12 { 13 UdpClient udpClient = new UdpClient(8001); 14 try 15 { 16 Console.WriteLine("向服务器发送数据:{0}",sendString); 17 byte[] sendBytes = Encoding.Unicode.GetBytes(sendString); 18 udpClient.Send(sendBytes, sendBytes.Length, "127.0.0.1", 8000); 19 if(sendString == "quit") 20 { 21 Console.WriteLine("已经向对方发送quit消息,请按回车键退出程序"); 22 return; 23 } 24 25 IPEndPoint myHost = null; 26 byte[] getBytes = udpClient.Receive(ref myHost); 27 string getString = Encoding.Unicode.GetString(getBytes); 28 Console.WriteLine("接收信息:{0}",getString); 29 udpClient.Close(); 30 Console.ReadLine(); 31 32 } 33 catch(Exception ex) 34 { 35 Console.WriteLine(ex.Message); 36 } 37 } 38 }
运行结果:
服务器
客户端
当然,可以做成从控制台读取文本再进行发送。
标签:
原文地址:http://www.cnblogs.com/zhaotianff/p/5545556.html