Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)qqpublished in(发表于) 2014/7/11 9:24:07 C#教程:开发UDP聊天程序使用实例
C#教程:开发UDP聊天程序使用实例|方法
开发UDP聊天程序本节将通过一个实例来讲解如何利用UDP开发多点聊天室程序。首先应在不同的计算机中运行聊天室服务程序,然后打开相应的客户发送端窗体,在客户发送端窗体的文本框中输入与之聊天的计算机IP地址,然后在“发送聊天信息”文本框中输入聊天信息,单击【发送】即可以将信息发送到目标计算机中。实例运行结果如图1和图2所示。图1 发送信息窗体图2 信息提示窗体服务器端实现的具体步骤如下所示。(1)在VS2005工程中添加一个窗体。(2)首先在代码设计器窗口中引入using System.Net.Sockets和using System.Net命名空间。(3)程序主要代码。通过UdpClient类实例化一个新对象listener用于监听信息,同时实例化IPEndPoint类的一个新对象groupEP(指定任意IP地址和指定端口号)。将其作为listener对象Receive方法的参数,以达到广播的作用。代码如下:bool done = False;private const int listenPort = 11000; //设置端口private void StartListener(){UdpClient listener = new UdpClient(listenPort); 使用UDP协议IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort); //任意IP,try{while (!done)//使用永真循环另其一直处于监听状态{byte[] bytes = listener.Receive(ref groupEP);string strIP;strIP ="信息来自"+ groupEP.Address.ToString();//获得发信人的IPstring strInfo=Encoding.GetEncoding("gb2312").GetString(bytes, 0,bytes.Length);//获得信息MessageBox.Show(strInfo, strIP);}}catch (Exception e){Console.WriteLine(e.ToString());}finally{listener.Close();}}服务器端窗体加载时,调用StartListenter方法开启监听,实现代码如下:private void frmServer_Load(object sender, EventArgs e){this.Hide();//隐藏服务器端窗体StartListener(); //调用监听方法}客户端实现的具体步骤如下所示:(1)在VS2005项目中添加一个窗体。(2)在窗体中添加两个TextBox文本框,分别用于获得IP信息与发送信息。(3)在窗体中添加两个Button按钮和两个Label标签,它们分别用于激发事件和显示信息。(4)程序主要代码。public void Send(){Socket s = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);//实例化Socket对象//为了起到广播的作用、IP可以设在一个段内如.168.1.255IPAddress broadcast = IPAddress.Parse(this.textBox2.Text.ToString());byte[] sendbuf =Encoding.GetEncoding("gb2312").GetBytes(this.textBox1.Text.ToString());IPEndPoint ep = new IPEndPoint(broadcast, 11000);s.SendTo(sendbuf, ep);//发送信息}完整程序代码如下:★ ★★★★Form1.cs窗体代码文件完整程序代码★★★★★using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Net;using System.Net.Sockets;namespace udpSent{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void button1_Click(object sender, EventArgs e){Send();}public void Send(){Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp);//起到广播的作用在一个段内如192.168.1.255 都是1IPAddress broadcast = IPAddress.Parse(this.textBox2.Text.ToString());//byte[] sendbuf = Encoding.GetEncoding("gb2312").GetBytes(this.textBox1.Text.ToString());IPEndPoint ep = new IPEndPoint(broadcast, 11000);s.SendTo(sendbuf, ep);Console.WriteLine("Message sent to the broadcast address");Console.Read();}private void Form1_Load(object sender, EventArgs e){}}}★ ★★★★Form1.designer.cs窗体设计文件完整程序代码★★★★★namespace udpSent{partial class Form1{/// 赞 If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长) QQ:154298438 QQ:417480759
赞