使用UdpClient类进行编程
UdpClient类的使用方法
第一阶段 创建UdpClient实例
UdpClient udpClient = new UdpClient();
IPAddress remoteAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint iep = new IPEndPoint(remoteAddress, );
第二阶段 数据发送
byte[] sendBytes = System.Text.Encoding.Unicode.GetBytes("Hello C#");
udpClient.Send(sendBytes,sendBytes.Length,iep);
第二阶段 数据接收
IPEndPoint iep2 = new IPEndPoint(IPAddress.Any, );
byte[] receiveBytes = udpClient.Receive(ref iep2);
string getData = System.Text.Encoding.Unicode.GetString(receiveBytes);
第三阶段 连接关闭
udpClient.Close();
一般常用声明的方式如下
1 UdpClient udpClient2 = new UdpClient("127.0.0.1",8000);
2 udpClient2.Send(sendBytes, sendBytes.Length);
测试代码:
服务器程序:
class Program
{
static void Main(string[] args)
{
StartListener();
Console.ReadLine();
} private static void StartListener()
{
UdpClient udpServer = new UdpClient(); //服务器方的端口号为8000 IPEndPoint myHost = null; try
{
while(true)
{
Console.WriteLine("等待接收...");
byte[] getBytes = udpServer.Receive(ref myHost);
string getString = Encoding.Unicode.GetString(getBytes, , getBytes.Length);
Console.WriteLine("接收信息:{0}",getString);
if (getString == "quit")
break; //向客户端回送消息
string sendString = "你好,Client";
Console.WriteLine("发送消息:{0}", sendString);
byte[] sendBytes = Encoding.Unicode.GetBytes(sendString);
udpServer.Send(sendBytes, sendBytes.Length, "127.0.0.1", ); } udpServer.Close();
Console.WriteLine("Client已经退出,请按回车键退出"); }
catch(Exception e)
{
Console.WriteLine(e.Message);
} }
}
客户端程序:
class Program
{
static void Main(string[] args)
{
string sendString = "客户端发送";
Send(sendString);
Send("quit");
Console.WriteLine();
} private static void Send(string sendString)
{
UdpClient udpClient = new UdpClient();
try
{
Console.WriteLine("向服务器发送数据:{0}",sendString);
byte[] sendBytes = Encoding.Unicode.GetBytes(sendString);
udpClient.Send(sendBytes, sendBytes.Length, "127.0.0.1", );
if(sendString == "quit")
{
Console.WriteLine("已经向对方发送quit消息,请按回车键退出程序");
return;
} IPEndPoint myHost = null;
byte[] getBytes = udpClient.Receive(ref myHost);
string getString = Encoding.Unicode.GetString(getBytes);
Console.WriteLine("接收信息:{0}",getString);
udpClient.Close();
Console.ReadLine(); }
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
运行结果:
服务器
客户端
当然,可以做成从控制台读取文本再进行发送。