代碼分享:UDP協(xié)議聊天工具的編寫
作者:佚名
文章中,我們分享了一個UDP協(xié)議的聊天器編寫代碼,希望對大家有所幫助。那么具體的源碼內(nèi)容請參考下文。
UDP協(xié)議我們在一些通訊軟件中經(jīng)常見到,而且也有不少朋友對這方面的編程感興趣。那么這里我們就來介紹一下UDP協(xié)議的聊天器的編寫過程。希望對大家有所幫助。代碼:
- 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協(xié)議組播的地址范圍內(nèi)的地址
- udpClient.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50);
- IPEndPoint remote = null;
- //接收從遠(yuǎn)程主機發(fā)送過來的信息
- while (true)
- {
- try
- {
- //關(guān)閉udpClient時此句會產(chǎn)生異常
- byte[] bytes = udpClient.Receive(ref remote);
- string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
- AppendString(string.Format("來自{0}:{1}", remote, str));
- }
- catch
- {
- //退出循環(huán),結(jié)束線程
- break;
- }
- }
- }
- private void btnSend_Click(object sender, EventArgs e)
- {
- UdpClient myUdpClient = new UdpClient();
- try
- {
- //允許發(fā)送和接收廣播數(shù)據(jù)報
- myUdpClient.EnableBroadcast = true;
- //必須使用組播地址范圍內(nèi)的地址
- IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), port);
- //將發(fā)送內(nèi)容轉(zhuǎn)換為字節(jié)數(shù)組
- byte[] bytes = Encoding.UTF8.GetBytes(txbSend.Text);
- //向子網(wǎng)發(fā)送信息
- myUdpClient.Send(bytes, bytes.Length, iep);
- txbSend.Clear();
- txbSend.Focus();
- }
- catch (Exception err)
- {
- MessageBox.Show(err.Message, "發(fā)送失敗");
- }
- finally
- {
- myUdpClient.Close();
- }
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- Thread receiveThread = new Thread(new ThreadStart(ReceiveData));
- //將線程設(shè)為后臺運行
- receiveThread.IsBackground = true;
- receiveThread.Start();
- }
- private void Form1_FormClosing(object sender, FormClosingEventArgs e)
- {
- udpClient.Close();
- }
- }
- }
以上就是全部的UDP協(xié)議聊天器的編寫代碼了。
本文出自 “gauyanm” 博客,請務(wù)必保留此出處http://gauyanm.blog.51cto.com/629619/340047
責(zé)任編輯:佟健
來源:
TT網(wǎng)絡(luò)