欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#使用udp如何實(shí)現(xiàn)消息的接收和發(fā)送

 更新時間:2023年02月26日 14:25:01   作者:王者無雙  
這篇文章主要介紹了C#使用udp如何實(shí)現(xiàn)消息的接收和發(fā)送問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

使用udp實(shí)現(xiàn)消息的接收和發(fā)送

代碼比較簡單,但是別忘記關(guān)閉防火墻進(jìn)行測試。

首先便是服務(wù)端,使用Socket進(jìn)行實(shí)現(xiàn),參考代碼如下:

? ? ? ? private static Socket udpServer;
? ? ? ? static void startUdpReceive()
? ? ? ? {
? ? ? ? ? ? Console.WriteLine("------startUdpReceive--");
? ? ? ? ? ? udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
? ? ? ? ? ? udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.106"), 10023));
? ? ? ? ? ? new Thread(ReceiveMessage)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? IsBackground = true
? ? ? ? ? ? }.Start();
? ? ? ? }
?
? ? ? ? private static void ReceiveMessage()
? ? ? ? {
? ? ? ? ? ? Console.WriteLine("------ReceiveMessage--");
? ? ? ? ? ? while (true)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? byte[] data = new byte[1024];
? ? ? ? ? ? ? ? EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
? ? ? ? ? ? ? ? int count = udpServer.ReceiveFrom(data, ref endPoint);
? ? ? ? ? ? ? ? if (count > 0)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? string message = Encoding.UTF8.GetString(data, 0, count);
? ? ? ? ? ? ? ? ? ? Console.WriteLine
? ? ? ? ? ? ? ? ? ? ? ? ("-----從ip" + (endPoint as IPEndPoint).Address.ToString()
? ? ? ? ? ? ? ? ? ? ? ? + ":" + (endPoint as IPEndPoint).Port + "Get" + message);
? ? ? ? ? ? ? ? }
?
? ? ? ? ? ? }
? ? ? ? }

在綁定socket端口的時候,需要提供綁定的ip和端口號,如這里是

udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.106"), 10023));

本機(jī)ip是是192.168.2.106,綁定端口是10023。然后使用while循環(huán)監(jiān)聽消息。對于本機(jī)來說,也可以使用 udpServer.Bind(new IPEndPoint(IPAddress.Any, 10023)); 只綁定端口,對于ip則不限制。

也可以不用Socket而是直接使用UdpClient類來寫接收端,效果類似:

? ? ? ? static UdpClient udpcRecv;
? ? ? ? public static void UdpServices()
? ? ? ? {
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? IPAddress ip = IPAddress.Parse("192.168.2.106");
? ? ? ? ? ? ? ? IPEndPoint remoteIpep = new IPEndPoint(ip, 10023);
? ? ? ? ? ? ? ? udpcRecv = new UdpClient(remoteIpep);
? ? ? ? ? ? ? ? Thread thrRecv = new Thread(ReceiveMessage22);
? ? ? ? ? ? ? ? thrRecv.IsBackground = true;
? ? ? ? ? ? ? ? thrRecv.Start();
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? MessageBox.Show("錯誤", "請檢查網(wǎng)絡(luò)");
? ? ? ? ? ? }
?
? ? ? ? }
?
?
? ? ? ? private static void ReceiveMessage22()
? ? ? ? {
? ? ? ? ? ? IPEndPoint remoteIpep = new IPEndPoint(IPAddress.Any, 0);
? ? ? ? ? ? Console.WriteLine("-----remoteIpep:" + remoteIpep.Address + ":" + remoteIpep.Port);
? ? ? ? ? ? while (true)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? try
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? byte[] bytRecv = udpcRecv.Receive(ref remoteIpep);
? ? ? ? ? ? ? ? ? ? string message = Encoding.UTF8.GetString(
? ? ? ? ? ? ? ? ? ? ? ? bytRecv, 0, bytRecv.Length);
? ? ? ? ? ? ? ? ? ? Console.WriteLine("-----reveice ?message:" + message);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? MessageBox.Show("UDP異常", ex.Message);
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }

接下來是發(fā)送端:

? ? ? ? ? ? UdpClient udpClient = new UdpClient();
? ? ? ? ? ? try
? ? ? ? ? ? {
? ? ? ? ? ? ? ? udpClient.Connect("192.168.2.106", 10023);
? ? ? ? ? ? ? ? Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there??????");
? ? ? ? ? ? ? ? udpClient.Send(sendBytes, sendBytes.Length);
? ? ? ? ? ? }
? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? {
? ? ? ? ? ? ? ? Console.WriteLine(ex.ToString());
? ? ? ? ? ? }

如果代碼爆紅則應(yīng)該是導(dǎo)包的問題,加入以下即可。

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.Net.NetworkInformation;
using System.Management;
using System.Threading;

上面都寫好后可以測試了,但是我卻遇到了問題,后面才知道是電腦端防火墻沒開導(dǎo)致,所以和電腦端調(diào)試網(wǎng)絡(luò)通信的時候,需要關(guān)閉防火墻,才能收到數(shù)據(jù)。

C# 運(yùn)用UDP

面試的時候偶爾會問到UDP和TCP的一個區(qū)別。

  • TCP是一種面向連接的、可靠的、基于字節(jié)流的傳輸層通信協(xié)議。舉例:打電話,需要雙方都接通,才能進(jìn)行對話。特點(diǎn):效率低,數(shù)據(jù)傳輸比較安全。
  • UDP是一種面向無連接的傳輸層通信協(xié)議。舉例:發(fā)短信,不需要雙方建立連接,但是,數(shù)據(jù)報的大小應(yīng)限制在64k以內(nèi)。特點(diǎn):效率高,數(shù)據(jù)傳輸不安全,容易丟包

然后發(fā)現(xiàn)在網(wǎng)上查找關(guān)于C#運(yùn)行UDP的實(shí)例,確實(shí)不好找,雜亂無章。痛定思痛!

進(jìn)行一個簡單的發(fā)送和接收測試。

目前,UDP本人親自用過的場景,客戶端和服務(wù)端需要進(jìn)行數(shù)據(jù)傳輸,但是服務(wù)端,在開始時是連接的別的網(wǎng)絡(luò),切換過來之后,并不能知道當(dāng)前的一個具體的IP地址。但是客戶端的IP地址是固定的,此種場景下,服務(wù)端網(wǎng)絡(luò)切換過來之后,建立UDP服務(wù)端,像指定的客戶端(IP地址和端口號)發(fā)送數(shù)據(jù),即可知道當(dāng)前服務(wù)端的ip地址。

服務(wù)端界面

 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyTest.UDP
{
    public partial class UDP_Sever : Form
    {
        IPEndPoint remotePoint;
        UdpClient sever = null;

        public UDP_Sever()
        {
            InitializeComponent();
        }
              
        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress remoteIP = IPAddress.Parse(textBox1.Text.Trim()); //假設(shè)發(fā)送給這個IP
            int remotePort =int.Parse(textBox2.Text.Trim());
            remotePoint = new IPEndPoint(remoteIP, remotePort);//實(shí)例化一個遠(yuǎn)程端點(diǎn)
            sever = new UdpClient();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(textBox3.Text.Trim()))
            {
                string sendString = textBox3.Text.Trim();//要發(fā)送的字符串
                byte[] sendData = Encoding.Default.GetBytes(sendString);//要發(fā)送的字節(jié)數(shù)組
                sever.Send(sendData, sendData.Length, remotePoint);//將數(shù)據(jù)發(fā)送到遠(yuǎn)程端點(diǎn)
                textBox3.Text = "";
            }
        }

        private void UDP_Sever_FormClosing(object sender, FormClosingEventArgs e)
        {
            sever.Close();
        }
    }
}

客戶端界面

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MyTest.UDP
{
    public partial class UDP_Client : Form
    {
        UdpClient client = null;
        IPEndPoint remotePoint;
        string receiveString = null;
        byte[] receiveData = null;


        public UDP_Client()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {         
            //實(shí)例化一個遠(yuǎn)程端點(diǎn),IP和端口可以隨意指定,等調(diào)用client.Receive(ref remotePoint)時會將該端點(diǎn)改成真正發(fā)送端端點(diǎn)
            remotePoint = new IPEndPoint(IPAddress.Any, 0);
            client = new UdpClient(int.Parse(textBox2.Text.Trim()));

            Thread thread = new Thread(Revice);
            thread.IsBackground = true;
            thread.Start();
        }
        private void Revice()
        {
            while (true)
            {             
                receiveData = client.Receive(ref remotePoint);//接收數(shù)據(jù)
                receiveString = Encoding.Default.GetString(receiveData);
                listBox1.Items.Add(remotePoint.Address.ToString()+":"+ receiveString);               
            }
        }
    }
}

親測有效!

總結(jié)

以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論