![](https://csdnimg.cn/release/download_crawler_static/86290586/bg3.jpg)
实验二 3
{
//获取本机可用 IP 地址
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
ip = ips[ips.Length - 1];
remoteIp = ip;
textBoxRemoteIP.Text = remoteIp.ToString();
textBoxSend.Text = " 你好!";
//创建一个线程接收远程主机发来的信息
Thread myThread = new Thread(ReceiveData);
//将线程设为后台运行
myThread.IsBackground = true;
myThread.Start();
textBoxSend.Focus();
main_wnd_handle = this.Handle;
}
工作线程与窗体线程间通过共享的全局变量来传递信息,重载窗体消息处理函数处理自定
义消息:
protected override void DefWndProc(ref Message m)
{//窗体消息处理重载
switch (m.Msg)
{
case RECV_DATA:
listBoxReceive.Items.Add(string.Format(" 来自 {0}:{1}", remote, receiveMessage));
listBoxReceive.SelectedIndex = listBoxReceive.Items.Count - 1;
listBoxReceive.ClearSelected();
break;
case SEND_DATA:
listBoxStatus.Items.Add(string.Format(" 向 {0} 发送:{1}", RemoteIp, sendMessage));
textBoxSend.Text = "";
textBoxSend.Focus();
break;
default:
base.DefWndProc(ref m);
break;
}
}
接收 UDP 数据线程代码,这里使用了循环结构,因此这个线程将一直运行而不结束:
private void ReceiveData()
{
IPEndPoint local = new IPEndPoint(ip, port);
3