private UdpClient client = new UdpClient(12345);
//ThreadPool.QueueUserWorkItem(recvHandler); // 执行接收数据线程
private void recvHandler(object obj)
{
while (client != null) {
IPEndPoint ipEP = new IPEndPoint(IPAddress.Any, 0);
byte[] recvData = client.Receive(ref ipEP);
if(recvData.Length>0){
this.Invoke(new Action(AsyncState =>{
this.textBox1.Text += Encoding.Default.GetString(AsyncState)+"\r\n"; // 显示接收到的字符串
}), recvData);
}
}
//向指定客户端发送数据
private void sendData(byte[] data, string ip, int port)
{
client.Send(data, data.Length, new IPEndPoint(IPAddress.Parse(ip), port));
}
我写在控制程序里了。主程序开启一个新线程做为服务器,在12900端口上收听。之后开始客户端循环,每次输入一行字,发给主机(本例里是同一主机 loopback)
class Program
{
static void Main(string[] args)
{
// 启动服务器
ThreadPool.QueueUserWorkItem(new WaitCallback(RunUdpServer));
UdpClient uc = new UdpClient(12901);
// 指定发送的主机名
IPEndPoint epHost = new IPEndPoint(IPAddress.Loopback, 12900); //127.0.0.1
while(true)
{
Console.Write("输入要发送的内容:");
string s = Console.ReadLine();
var data = Encoding.UTF8.GetBytes(s);
uc.Send(data, data.Length, epHost);
Thread.Sleep(100);
}
}
private static void RunUdpServer(object para)
{
UdpClient uc = new UdpClient(12900);
// 指定监听的网络区域
IPEndPoint epListen = new IPEndPoint(IPAddress.Any, 0); //侦听所有的网络活动
while (true)
{
Application.DoEvents();
try
{
byte[] recb = uc.Receive(ref epListen);
Console.WriteLine("Server: recived from {0}:{1}", epListen.Address, epListen.Port);
Console.WriteLine(Encoding.UTF8.GetString(recb));
}
catch (Exception ex)
{
Console.WriteLine("出现错误:" + ex.Message.ToString());
break;
}
}
}
}