UDP协议我们在一些通讯软件中经常见到,而且也有不少朋友对这方面的编程感兴趣。那么这里我们就来介绍一下UDP协议的聊天器的编写过程。希望对大家有所帮助。代码:
- 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;
- using System.Threading;
- namespace MulticastExample
- {
- public partial class Form1 : Form
- {
- delegate void AppendStringCallback(string text);
- AppendStringCallback appendStringCallback;
- //使用的接收端口号
- private int port = 8001;
- private UdpClient udpClient;
- public Form1()
- {
- InitializeComponent();
- appendStringCallback = new AppendStringCallback(AppendString);
- }
- private void AppendString(string text)
- {
- if (richTextBox1.InvokeRequired)
- {
- richTextBox1.Invoke(appendStringCallback, text);
- }
- else
- {
- richTextBox1.AppendText(text + "\r\n");
- }
- }
- private void ReceiveData()
- {
- udpClient = new UdpClient(port);
- //必须使用UDP协议组播的地址范围内的地址
- udpClient.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 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 btnSend_Click(object sender, EventArgs e)
- {
- UdpClient myUdpClient = new UdpClient();
- try
- {
- //允许发送和接收广播数据报
- myUdpClient.EnableBroadcast = true;
- //必须使用组播地址范围内的地址
- IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), port);
- //将发送内容转换为字节数组
- byte[] bytes = Encoding.UTF8.GetBytes(txbSend.Text);
- //向子网发送信息
- myUdpClient.Send(bytes, bytes.Length, iep);
- txbSend.Clear();
- txbSend.Focus();
- }
- catch (Exception err)
- {
- MessageBox.Show(err.Message, "发送失败");
- }
- finally
- {
- myUdpClient.Close();
- }
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
- //将线程设为后台运行
- receiveThread.IsBackground = true;
- receiveThread.Start();
- }
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- udpClient.Close();
- }
- }
- }
以上就是全部的UDP协议聊天器的编写代码了。
本文出自 “gauyanm” 博客,请务必保留此出处http://gauyanm.blog.51cto.com/629619/340047