UDP编程示例Word文档格式.docx
《UDP编程示例Word文档格式.docx》由会员分享,可在线阅读,更多相关《UDP编程示例Word文档格式.docx(24页珍藏版)》请在冰点文库上搜索。
![UDP编程示例Word文档格式.docx](https://file1.bingdoc.com/fileroot1/2023-5/8/c7e76eba-08c6-4994-85a2-3271b496a165/c7e76eba-08c6-4994-85a2-3271b496a1651.gif)
publicpartialclassFormChat:
Form
{
delegatevoidAddListBoxItemCallback(stringtext);
AddListBoxItemCallbacklistBoxCallback;
//使用的接收端口号
privateintport=8001;
privateUdpClientudpClient;
publicFormChat()
InitializeComponent();
//初始化
listBoxCallback=newAddListBoxItemCallback(AddListBoxItem);
}
privatevoidAddListBoxItem(stringtext)
//如果listBoxReceive被不同的线程访问则通过委托处理;
if(listBoxReceive.InvokeRequired)
//C#中禁止跨线程直接访问控件,InvokeRequired是为了解决这个问题而产生的,当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它。
this.Invoke(listBoxCallback,text);
else
listBoxReceive.Items.Add(text);
listBoxReceive.SelectedIndex=listBoxReceive.Items.Count-1;
///<
summary>
///在后台运行的接收线程
/summary>
privatevoidReceiveData()
//在本机指定的端口接收
udpClient=newUdpClient(port);
IPEndPointremote=null;
//接收从远程主机发送过来的信息;
while(true)
try
//关闭udpClient时此句会产生异常
byte[]bytes=udpClient.Receive(refremote);
stringstr=Encoding.UTF8.GetString(bytes,0,bytes.Length);
AddListBoxItem(string.Format("
来自{0}:
{1}"
remote,str));
catch
//退出循环,结束线程
break;
///发送数据到远程主机
privatevoidsendData()
UdpClientmyUdpClient=newUdpClient();
IPAddressremoteIP;
if(IPAddress.TryParse(textBoxRemoteIP.Text,outremoteIP)==false)
//如果字符串包含非数值字符或者所包含的数值对于指定的特定类型而言太大或太小,TryParse
都将返回false并将out参数设置为零。
否则,它将返回true,并且将out参数设置为字符串的数值
MessageBox.Show("
远程IP格式不正确"
);
return;
IPEndPointiep=newIPEndPoint(remoteIP,port);
byte[]bytes=System.Text.Encoding.UTF8.GetBytes(textBoxSend.Text);
myUdpClient.Send(bytes,bytes.Length,iep);
textBoxSend.Clear();
myUdpClient.Close();
textBoxSend.Focus();
catch(Exceptionerr)
MessageBox.Show(err.Message,"
发送失败"
finally
privatevoidFormChat_Load(objectsender,EventArgse)
//设置listBox样式
listBoxReceive.HorizontalScrollbar=true;
listBoxReceive.Dock=DockStyle.Fill;
//扩展填满单元格
//获取本机第一个可用IP地址
IPAddressmyIP=(IPAddress)Dns.GetHostAddresses(Dns.GetHostName()).GetValue(0);
//为了在同一台机器调试,此IP也作为默认远程IP
textBoxRemoteIP.Text=myIP.ToString();
//创建一个线程接收远程主机发来的信息
ThreadmyThread=newThread(newThreadStart(ReceiveData));
//将线程设为后台运行
myThread.IsBackground=true;
myThread.Start();
///单击发送按钮触发的事件
privatevoidbuttonSend_Click(objectsender,EventArgse)
sendData();
///在textBoxSend中按下并释放Enter键后触发的事件
privatevoidtextBoxData_KeyPress(objectsender,KeyPressEventArgse)
if(e.KeyChar==(char)Keys.Enter)
privatevoidFormChat_FormClosing(objectsender,FormClosingEventArgse)
udpClient.Close();
}
(3)按<
F5>
键编译并执行,向默认远程主机发送一些信息,运行效果如图2所示。
【例2】编写一个Windows应用程序,向子网发送广播信息,同时接收子网中的任意主机发送的广播信息。
(1)创建一个名为BroadcastExample的Windows应用程序,修改Form1.cs为FormBroadcast.cs,设计界面如图3所示。
namespaceBroadcastExample
publicpartialclassFormBroacast:
delegatevoidAppendStringCallback(stringtext);
AppendStringCallbackappendStringCallback;
publicFormBroacast()
appendStringCallback=newAppendStringCallback(AppendString);
privatevoidAppendString(stringtext)
if(richTextBox1.InvokeRequired==true)
this.Invoke(appendStringCallback,text);
richTextBox1.AppendText(text+"
\r\n"
AppendString(string.Format("
//让其自动提供子网中的IP广播地址
IPEndPointiep=newIPEndPoint(IPAddress.Broadcast,8001);
//允许发送和接收广播数据报
myUdpClient.EnableBroadcast=true;
//将发送内容转换为字节数组
byte[]bytes=System.Text.Encoding.UTF8.GetBytes(textBox1.Text);
//向子网发送信息
textBox1.Clear();
textBox1.Focus();
privatevoidFormBroacast_Load(objectsender,EventArgse)
privatevoidFormBroacast_FormClosing(objectsender,FormClosingEventArgse)
(3)按<
键编译并执行,发送一些信息,观察结果。
【例3】编写一个Windows应用程序,利用组播技术向子网发送组播信息,同时接收组播的信息。
(1)创建一个名为MulticastExample的Windows应用程序,修改Form1.cs为FormMulticast.cs,设计界面如图4所示。
namespaceMulticastExample
publicpartialclassFormMulticast:
publicFormMulticast()
//必须使用组播地址范围内的地址
udpClient.JoinMulticastGroup(IPAddress.Parse("
224.0.0.1"
));
udpClient.Ttl=50;
IPEndPointiep=newIPEndPoint(IPAddress.Parse("
),8001);
privatevoidFormMulticast_Load(objectsender,EventArgse)
privatevoidFormMulticast_FormClosing(objectsender,FormClosingEventArgse)
【例4】编写一个Windows应用程序,利用组播技术进行网络会议讨论。
(1)创建一个名为“NetMeetingExample”的Windows应用程序,修改Form1.cs为FormMeeting.cs,设计界面如图5所示。
namespaceNetMeetingExample
publicpartialclassFormMeeting:
privateenumListBoxOperation{AddItem,RemoveItem};
privatedelegatevoidSetListBoxItemCallback(
ListBoxlistbox,stringtext,ListBoxOperationoperation);
SetListBoxItemCallbacklistBoxCallback;
//使用的IP地址
privateIPAddressip=IPAddress.Parse("
224.100.0.1"
publicFormMeeting()
listBoxCallback=newSetListBoxItemCallback(SetListBoxItem);
privatevoidSetListBoxItem(ListBoxlistbox,stringtext,ListBoxOperationoperation)
if(listbox.InvokeRequired==true)
this.Invoke(listBoxCallback,listbox,text,operation);
if(operation==ListBoxOperation.AddItem)
if(listbox==listBoxAddress)
if(listbox.Items.Contains(text)==false)
listbox.Items.Add(text);
listbox.SelectedIndex=listbox.Items.Count-1;
listbox.ClearSelected();
elseif(operation==ListBoxOperation.RemoveItem)
listbox.Items.Remove(text);
privatevoidSendToAll(stringsendString)
IPEndPointiep=newIPEndPoint(ip,port);
byte[]bytes=System.Text.Encoding.UTF8.GetBytes(sendString);