UDP编程示例
【例1】UdpClient 使用示例——UDP 网络聊天工具。
(1) 创建一个名为UdpChatExample 的Windows 应用程序,修改Form1.cs 为FormChat.cs ,设计界面如图1所示。
(2) 添加对应的代码,源程序如下:
using System;
using System.Collections.Generic;
using https://www.360docs.net/doc/df7346846.html,ponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//添加的命名空间引用
using https://www.360docs.net/doc/df7346846.html,;
using https://www.360docs.net/doc/df7346846.html,.Sockets;
using System.Threading;
namespace UdpChatExample
{
public partial class FormChat : Form
{
delegate void AddListBoxItemCallback(string text);
AddListBoxItemCallback listBoxCallback;
//使用的接收端口号
private int port = 8001;
private UdpClient udpClient;
public FormChat()
{
InitializeComponent(); //初始化
图1 例1设计界面
listBoxCallback = new AddListBoxItemCallback(AddListBoxItem);
}
private void AddListBoxItem(string text)
{
//如果listBoxReceive被不同的线程访问则通过委托处理;
if (listBoxReceive.InvokeRequired)
// C#中禁止跨线程直接访问控件,InvokeRequired是为了解决这个问题而产生的,当一个控件的InvokeRequired属性值为真时,说明有一个创建它以外的线程想访问它。
{
this.Invoke(listBoxCallback, text);
}
else
{
listBoxReceive.Items.Add(text);
listBoxReceive.SelectedIndex = listBoxReceive.Items.Count - 1;
}
}
///
/// 在后台运行的接收线程
///
private void ReceiveData()
{
//在本机指定的端口接收
udpClient = new UdpClient(port);
IPEndPoint remote = null;
//接收从远程主机发送过来的信息;
while (true)
{
try
{
//关闭udpClient时此句会产生异常
byte[] bytes = udpClient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
AddListBoxItem(string.Format("来自{0}:{1}", remote, str));
}
catch
{
//退出循环,结束线程
break;
}
}
}
///
/// 发送数据到远程主机
///
private void sendData()
{
UdpClient myUdpClient = new UdpClient();
IPAddress remoteIP;
if (IPAddress.TryParse(textBoxRemoteIP.Text, out remoteIP) == false)
//如果字符串包含非数值字符或者所包含的数值对于指定的特定类型而言太大或太小,TryParse都将返回false 并将out 参数设置为零。否则,它将返回true,并且将out 参数设置为字符串的数值
{
MessageBox.Show("远程IP格式不正确");
return;
}
IPEndPoint iep = new IPEndPoint(remoteIP, port);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBoxSend.Text);
try
{
myUdpClient.Send(bytes, bytes.Length, iep);
textBoxSend.Clear();
myUdpClient.Close();
textBoxSend.Focus();
}
catch (Exception err)
{
MessageBox.Show(err.Message, "发送失败");
}
finally
{
myUdpClient.Close();
}
}
private void FormChat_Load(object sender, EventArgs e)
{
//设置listBox样式
listBoxReceive.HorizontalScrollbar = true;
listBoxReceive.Dock = DockStyle.Fill; //扩展填满单元格
//获取本机第一个可用IP地址
IPAddress myIP = (IPAddress)Dns.GetHostAddresses(Dns.GetHostName()).GetValue(0);
//为了在同一台机器调试,此IP也作为默认远程IP
textBoxRemoteIP.Text = myIP.ToString();
//创建一个线程接收远程主机发来的信息
Thread myThread = new Thread(new ThreadStart(ReceiveData));
//将线程设为后台运行
myThread.IsBackground = true;
myThread.Start();
textBoxSend.Focus();
}
///
/// 单击发送按钮触发的事件
///
private void buttonSend_Click(object sender, EventArgs e)
{
sendData();
}
///
/// 在textBoxSend中按下并释放Enter键后触发的事件
///
private void textBoxData_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter)
sendData();
}
private void FormChat_FormClosing(object sender, FormClosingEventArgs e)
{
udpClient.Close();
}
}
}
(3) 按
【例2】编写一个Windows 应用程序,向子网发送广播信息,同时接收子网中的任意主机发送的广播信息。
(1) 创建一个名为BroadcastExample 的Windows 应用程序,修改Form1.cs 为FormBroadcast.cs ,设计界面如图3所示。
(2) 添加对应的代码,源程序如下:
using System;
using System.Collections.Generic;
using https://www.360docs.net/doc/df7346846.html,ponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//添加的命名空间引用
using https://www.360docs.net/doc/df7346846.html,;
using https://www.360docs.net/doc/df7346846.html,.Sockets;
using System.Threading;
namespace BroadcastExample {
图3 例2的设计界面
图6-2 例6-1的运行效果
public partial class FormBroacast : Form
{
delegate void AppendStringCallback(string text);
AppendStringCallback appendStringCallback;
//使用的接收端口号
private int port = 8001;
private UdpClient udpClient;
public FormBroacast()
{
InitializeComponent();
appendStringCallback = new AppendStringCallback(AppendString);
}
private void AppendString(string text)
{
if (richTextBox1.InvokeRequired == true)
{
this.Invoke(appendStringCallback, text);
}
else
{
richTextBox1.AppendText(text + "\r\n");
}
}
///
/// 在后台运行的接收线程
///
private void ReceiveData()
{
//在本机指定的端口接收
udpClient = new UdpClient(port);
IPEndPoint remote = null;
//接收从远程主机发送过来的信息;
while (true)
{
try
{
//关闭udpClient时此句会产生异常
byte[] bytes = udpClient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
AppendString(string.Format("来自{0}:{1}", remote, str));
}
catch
{
//退出循环,结束线程
break;
}
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
UdpClient myUdpClient = new UdpClient();
try
{
//让其自动提供子网中的IP广播地址
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 8001);
//允许发送和接收广播数据报
myUdpClient.EnableBroadcast = true;
//将发送内容转换为字节数组
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBox1.Text);
//向子网发送信息
myUdpClient.Send(bytes, bytes.Length, iep);
textBox1.Clear();
textBox1.Focus();
}
catch (Exception err)
{
MessageBox.Show(err.Message, "发送失败");
}
finally
{
myUdpClient.Close();
}
}
private void FormBroacast_Load(object sender, EventArgs e)
{
Thread myThread = new Thread(new ThreadStart(ReceiveData));
//将线程设为后台运行
myThread.IsBackground = true;
myThread.Start();
}
private void FormBroacast_FormClosing(object sender, FormClosingEventArgs e)
{
udpClient.Close();
}
}
}
(3) 按
【例3】编写一个Windows 应用程序,利用组播技术向子网发送组播信息,同时接收组播的信息。
(1) 创建一个名为MulticastExample 的Windows 应用程序,修改Form1.cs 为FormMulticast.cs ,设计界面如图4所示。
(2) 添加对应的代码,源程序如下:
using System;
using System.Collections.Generic;
using https://www.360docs.net/doc/df7346846.html,ponentModel;
using System.Data;
using System.Drawing;
using System.Text; using System.Windows.Forms;
图4 例3的设计界面
//添加的命名空间引用
using https://www.360docs.net/doc/df7346846.html,;
using https://www.360docs.net/doc/df7346846.html,.Sockets;
using System.Threading;
namespace MulticastExample
{
public partial class FormMulticast : Form
{
delegate void AppendStringCallback(string text);
AppendStringCallback appendStringCallback;
//使用的接收端口号
private int port = 8001;
private UdpClient udpClient;
public FormMulticast()
{
InitializeComponent();
appendStringCallback = new AppendStringCallback(AppendString);
}
private void AppendString(string text)
{
if (richTextBox1.InvokeRequired == true)
{
this.Invoke(appendStringCallback, text);
}
else
{
richTextBox1.AppendText(text + "\r\n");
}
}
private void ReceiveData()
{
//在本机指定的端口接收
udpClient = new UdpClient(port);
//必须使用组播地址范围内的地址
udpClient.JoinMulticastGroup(IPAddress.Parse("224.0.0.1"));
udpClient.Ttl = 50;
IPEndPoint remote = null;
//接收从远程主机发送过来的信息;
while (true)
{
try
{
//关闭udpClient时此句会产生异常
byte[] bytes = udpClient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
AppendString(string.Format("来自{0}:{1}", remote, str));
}
catch
{
//退出循环,结束线程
break;
}
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
UdpClient myUdpClient = new UdpClient();
//允许发送和接收广播数据报
myUdpClient.EnableBroadcast = true;
//必须使用组播地址范围内的地址
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.0.0.1"), 8001);
//将发送内容转换为字节数组
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(textBox1.Text);
try
{
//向子网发送信息
myUdpClient.Send(bytes, bytes.Length, iep);
textBox1.Clear();
textBox1.Focus();
}
catch (Exception err)
{
MessageBox.Show(err.Message, "发送失败");
}
finally
{
myUdpClient.Close();
}
}
private void FormMulticast_Load(object sender, EventArgs e)
{
Thread myThread = new Thread(new ThreadStart(ReceiveData));
myThread.Start();
}
private void FormMulticast_FormClosing(object sender, FormClosingEventArgs e)
{
udpClient.Close();
}
}
}
(3) 按
【例4】编写一个Windows应用程序,利用组播技术进行网络会议讨论。
(1) 创建一个名为“NetMeetingExample”的Windows应用程序,修改Form1.cs为FormMeeting.cs,设计界面如图5所示。
(2) 添加对应的代码,源程序如下:
using System;
using System.Collections.Generic;
using https://www.360docs.net/doc/df7346846.html,ponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//添加的命名空间引用
using https://www.360docs.net/doc/df7346846.html,;
using https://www.360docs.net/doc/df7346846.html,.Sockets;
using System.Threading;
namespace NetMeetingExample
{
public partial class FormMeeting : Form
{
private enum ListBoxOperation { AddItem, RemoveItem };
private delegate void SetListBoxItemCallback(
ListBox listbox, string text, ListBoxOperation operation);
SetListBoxItemCallback listBoxCallback;
//使用的IP地址
private IPAddress ip = IPAddress.Parse("224.100.0.1");
//使用的接收端口号
private int port = 8001;
private UdpClient udpClient;
public FormMeeting()
{
InitializeComponent();
listBoxCallback = new SetListBoxItemCallback(SetListBoxItem);
}
private void SetListBoxItem(ListBox listbox, string text, ListBoxOperation operation) {
if (listbox.InvokeRequired == true)
{
this.Invoke(listBoxCallback, listbox, text, operation);
}
else
{
if (operation == ListBoxOperation.AddItem)
{
if (listbox == listBoxAddress)
{
if (listbox.Items.Contains(text) == false)
{
listbox.Items.Add(text);
}
}
else
{
listbox.Items.Add(text);
}
listbox.SelectedIndex = listbox.Items.Count - 1;
listbox.ClearSelected();
}
else if (operation == ListBoxOperation.RemoveItem)
{
listbox.Items.Remove(text);
}
}
}
private void SendToAll(string sendString)
{
UdpClient myUdpClient = new UdpClient();
//允许发送和接收广播数据报
myUdpClient.EnableBroadcast = true;
//必须使用组播地址范围内的地址
IPEndPoint iep = new IPEndPoint(ip, port);
//将发送内容转换为字节数组
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(sendString);
try
{
//向子网发送信息
myUdpClient.Send(bytes, bytes.Length, iep);
}
catch (Exception err)
{
MessageBox.Show(err.Message, "发送失败");
}
finally
{
myUdpClient.Close();
}
}
private void FormMeeting_Load(object sender, EventArgs e)
{
listBoxMessage.HorizontalScrollbar = true;
buttonLogin.Enabled = true;
buttonLogout.Enabled = false;
groupBoxRoom.Enabled = false;
}
///
/// 接收线程
///
private void ReceiveMessage()
{
udpClient = new UdpClient(port);
//必须使用组播地址范围内的地址
udpClient.JoinMulticastGroup(ip);
udpClient.Ttl = 50;
IPEndPoint remote = null;
while (true)
{
try
{
//关闭udpClient时此句会产生异常
byte[] bytes = udpClient.Receive(ref remote);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
string[] splitString = str.Split(',');
int s = splitString[0].Length;
switch (splitString[0])
{
case "Login": //进入会议室
SetListBoxItem(listBoxMessage,
string.Format("[{0}]进入。",
remote.Address), ListBoxOperation.AddItem);
string userListString = "List," + remote.Address.ToString();
for (int i = 0; i < listBoxAddress.Items.Count; i++)
{
userListString += "," + listBoxAddress.Items[i].ToString();
}
SendToAll(userListString);
break;
case "List": //参加会议人员名单
for (int i = 1; i < splitString.Length; i++)
{
SetListBoxItem(listBoxAddress,
splitString[i], ListBoxOperation.AddItem);
}
break;
case "Message": //发言内容
SetListBoxItem(listBoxMessage,
string.Format("[{0}]说:{1}", remote.Address, str.Substring(8)),
ListBoxOperation.AddItem);
break;
case "Logout": //退出会议室
SetListBoxItem(listBoxMessage,
string.Format("[{0}]退出。", remote.Address),
ListBoxOperation.AddItem);
SetListBoxItem(listBoxAddress,
remote.Address.ToString(), ListBoxOperation.RemoveItem);
break;
}
}
catch
{
//退出循环,结束线程
break;
}
}
}
private void textBoxMessage_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Return)
{
if (textBoxMessage.Text.Trim().Length > 0)
{
SendToAll("Message," + textBoxMessage.Text);
textBoxMessage.Text = "";
}
}
}
//窗体已关闭并指定关闭原因前触发的事件
private void Form1_FormClosing(object sender, FormClosingEventArgs e) {
if (buttonLogout.Enabled == true)
{
MessageBox.Show("请先离开会议室,然后再退出!", "",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
//不关闭窗体
e.Cancel = true;
}
}
//单击进入会议室按钮触发的事件
private void buttonLogin_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
Thread myThread = new Thread(new ThreadStart(ReceiveMessage));
myThread.Start();
//等待接收线程准备完毕
Thread.Sleep(1000);
SendToAll("Login");
buttonLogin.Enabled = false;
buttonLogout.Enabled = true;
groupBoxRoom.Enabled = true;
Cursor.Current = Cursors.Default;
}
//单击退出会议室按钮触发的事件
private void buttonLogout_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
SendToAll("Logout");
//等待接收线程处理完毕
Thread.Sleep(1000);
//结束接收线程
udpClient.Close();
buttonLogin.Enabled = true;
buttonLogout.Enabled = false;
groupBoxRoom.Enabled = false;
Cursor.Current = Cursors.Default;
}
}
}
(3) 同时在几台计算机上运行该程序,观察运行效果。