udpclient类应用实例 客户机程序
using System;using
using
namespace testUdpClient
{
class Class1
{
static void Main(string[]args)
{
string sendString="你好,继续努力";
Send(sendString);
Send("quit");
Console.ReadLine();
}
private static void Send(string message)
{
UdpClient udpClient=new udpClient(8001);
try
{
Console.WriteLine("向服务器发送数据:{0}",message);
byte[]sendBytes=System.Text.Encoding.Unicode.GetBytes(message);
udpClient.Send(sendBytes,sendBytes.Length,"127.0.0.1",8000);
if(message=="quit")
{
Console.WriteLine("已经向对方发送quit消息,请按回车键退出程序。");
return;
}
IPEndPoint myHost=null;
byte[]getBytes=udpClient.Receive(ref myHost);
string getString=System.Text.Encoding.Unicode.GetString(getBytes);
Console.WriteLine("接收消息:{0}",getString);
udpClient.Close();
}
catch(Exception err)
{
Console.WriteLine(err.ToString());
}
}
}
}