c#基于socket的UDP服务器和客户端实例
基于Udp協(xié)議是無連接模式通訊,占用資源少,響應(yīng)速度快,延時(shí)低。至于可靠性,可通過應(yīng)用層的控制來滿足。(不可靠連接)
使用Udp協(xié)議通訊需要具備以下幾個(gè)條件:
(1).建立一個(gè)套接字(Socket)
(2).綁定服務(wù)器端IP地址及端口號(hào)--服務(wù)器端
(3).通過SendTo()方法向指定主機(jī)發(fā)送消息 (需提供主機(jī)IP地址及端口)
(4).通過ReciveFrom()方法接收指定主機(jī)發(fā)送的消息 (需提供主機(jī)IP地址及端口)
?
下面用代碼實(shí)現(xiàn)簡(jiǎn)單的服務(wù)器---客戶端通信
服務(wù)器端:
| using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; namespace _023_socket編程_UDP協(xié)議_服務(wù)器端 { //3,接收數(shù)據(jù) static void ReceiveMessage() } |
客戶端:
| using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace _002_socket編程_udp協(xié)議_客戶端 { while (true)
|
執(zhí)行過程:
(1)啟動(dòng)服務(wù)器
(2)啟動(dòng)客戶端,并向服務(wù)器發(fā)送數(shù)據(jù)
//***************************2*************
C#使用UDP實(shí)現(xiàn)服務(wù)器與客戶端通信
TCP 必須建立在連接才可以進(jìn)行通信,
UDP不需要建立通信
但兩者都需要監(jiān)聽來接收消息
服務(wù)端
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading;namespace UDP_windows_服務(wù)器 {public partial class Form1 : Form{public Form1(){InitializeComponent();CheckForIllegalCrossThreadCalls = false;}/// <summary>/// 獲取本地IP/// </summary>private void label1_Click(object sender, EventArgs e){string ip = IPAddress.Any.ToString();textBox1.Text = ip;}Socket server;private void button1_Click(object sender, EventArgs e){//1.創(chuàng)建服務(wù)器端電話server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//2.創(chuàng)建手機(jī)卡IPAddress iP = IPAddress.Parse(textBox1.Text);IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox2.Text));//3.將電話卡插進(jìn)電話中(綁定端口號(hào)和IP)server.Bind(endPoint);listBox1.Items.Add("服務(wù)器已經(jīng)成功開啟!");//開啟接收消息線程Thread t = new Thread(ReciveMsg);t.IsBackground = true;t.Start();}/// <summary>/// 向特定ip的主機(jī)的端口發(fā)送數(shù)據(jù)/// </summary>tevoid SendMsg(){//string hostName = Dns.GetHostName(); //獲取本機(jī)名//IPHostEntry localhost = Dns.GetHostEntry(hostName); //獲取IPv6地址//IPAddress localaddr = localhost.AddressList[0];EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(textBox2.Text));string msg = textBox3.Text;server.SendTo(Encoding.UTF8.GetBytes(msg), point);}/// <summary>/// 接收發(fā)送給本機(jī)ip對(duì)應(yīng)端口號(hào)的數(shù)據(jù)/// </summary>void ReciveMsg(){while (true){EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用來保存發(fā)送方的ip和端口號(hào)byte[] buffer = new byte[1024 * 1024];int length = server.ReceiveFrom(buffer, ref point);//接收數(shù)據(jù)報(bào)string message = Encoding.UTF8.GetString(buffer, 0, length);listBox1.Items.Add(point.ToString() + ":" + message);}}private void button2_Click(object sender, EventArgs e){if (textBox3.Text != ""){//開啟發(fā)送消息線程Thread t2 = new Thread(SendMsg);t2.Start();}}} }客戶端
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Net.Sockets; using System.Net; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading;namespace UDP_windows_客戶端 {public partial class Form1 : Form{public Form1(){InitializeComponent();}/// <summary>/// 創(chuàng)建客戶端/// </summary>Socket client;private void button1_Click(object sender, EventArgs e){///創(chuàng)建客戶端client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);IPAddress iP = IPAddress.Parse(textBox1.Text);///端口號(hào)IPEndPoint endPoint = new IPEndPoint(iP, int.Parse(textBox2.Text));///建立與服務(wù)器的遠(yuǎn)程連接client.Connect(endPoint);///線程問題Thread thread = new Thread(ReciveMsg);thread.IsBackground = true;thread.Start(client);listBox1.Items.Add("客戶端已成功開啟!");}/// <summary>/// 向特定ip的主機(jī)的端口發(fā)送數(shù)據(jù)/// </summary>void SendMsg(){///獲取IP與端口號(hào)EndPoint point = new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text));///發(fā)送內(nèi)容string msg = textBox3.Text;///將數(shù)據(jù)發(fā)送到指定的ip的主機(jī)的端口client.SendTo(Encoding.UTF8.GetBytes(msg), point);}/// <summary>/// 接收發(fā)送給本機(jī)ip對(duì)應(yīng)端口號(hào)的數(shù)據(jù)/// </summary>void ReciveMsg(object o){Socket client = o as Socket;while (true){try{///用來保存發(fā)送方的ip和端口號(hào)EndPoint point = new IPEndPoint(IPAddress.Any, 0);///定義客戶端接收到的信息大小byte[] buffer = new byte[1024 * 1024];///接收到的信息大小(所占字節(jié)數(shù))int length = client.Receive(buffer);string message = Encoding.UTF8.GetString(buffer, 0, length);listBox1.Items.Add(point.ToString() + ":" + message);}catch (Exception){client.Close();}}}private void button2_Click(object sender, EventArgs e){if (textBox3.Text != ""){//開啟發(fā)送消息線程Thread t2 = new Thread(SendMsg);t2.Start();}listBox1.Items.Add(textBox3.Text);}private void Form1_Load(object sender, EventArgs e){}} }?
總結(jié)
以上是生活随笔為你收集整理的c#基于socket的UDP服务器和客户端实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springboot 项目输出 sql
- 下一篇: 解决 VUE: [Vue warn]: