UDP编程示例

相关主题
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

【例1】UdpClient 使用示例——UDP 网络聊天工具。

(1) 创建一个名为UdpChatExample 的Windows 应用程序,修改Form1.cs 为FormChat.cs ,设计界面如图1所示。

(2) 添加对应的代码,源程序如下:

using System;

using System.Collections.Generic;

using ponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

//添加的命名空间引用

using ;

using .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();

}

}

相关文档
最新文档