网络UDP 套接字

  • Post author:
  • Post category:其他




一、C#编写一个命令行/控制台程序

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
            Console.WriteLine("输出:");
            Console.ReadKey();
            for (int a = 0; a < 50; a = a + 1)
            {
                Console.WriteLine("hello cqjtu!重交物联2018级");
            }
            Console.ReadLine();
        }
    }
}

效果:

在这里插入图片描述



二、网络UDP 套接字

sever代码:

using System;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace sever
{
    class Class2
    {
        static void Main(string[] args)
        {
            UdpClient udpReceive = new UdpClient(11000);

            //设置远程主机,(IPAddress.Any, 0)代表接收所有IP所有端口发送的数据
            IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);//或 IPEndPoint remoteIpEndPoint = null;

            //监听数据,接收到数据后,把数据转换成字符串并输出
            Console.Write("连接成功!");

            byte[] receiveBytes = udpReceive.Receive(ref remoteIpEndPoint);
            string returnData = Encoding.ASCII.GetString(receiveBytes);
            for (int i = 0; i < 50; i++)
                Console.WriteLine(" " + returnData.ToString());
            Console.WriteLine("This message was sent from " + remoteIpEndPoint.Address.ToString() + " on their port number " + remoteIpEndPoint.Port.ToString());

            //关闭连接
            udpReceive.Close();


        }
    }
}

客户端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            UdpClient udpSender = new UdpClient(0);

            //连接到服务端并指定接收端口
            udpSender.Connect("localhost", 11000);
            Console.Write("连接成功!");
           
         //  byte[] sendBytes = Encoding.ASCII.GetBytes("hello cqjtu!重交物联2018级?");
        //        udpSender.Send(sendBytes, sendBytes.Length);

            string sendString = "hello cqjtu!重交物联2018级";//要发送的字符串
            string str = "hello cqjtu!重交物联2018级";
            byte[] sendBytes = Encoding.Default.GetBytes(str);
            udpSender.Send(sendBytes, sendBytes.Length);
            Console.Write("发送成功!");
            //关闭链接
            udpSender.Close();
        }
    }
}

先运行sever:

在这里插入图片描述

再运行client:

在这里插入图片描述

这时再打开sever的控制台:

在这里插入图片描述

出现中文乱码,将数据由字节数组改为字符串类型



三、C#编写一个简单的Form窗口程序

新建C#窗体程序,代码如下(同一主机)

若是不同主机,只需要在代码部分将两台主机ip地址变量修改,

并注释掉:

remoteip = ip;

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

namespace test
{
    public partial class Form1 : Form
    {
        private UdpClient receiveUdpClient;//接收用
        private UdpClient sendUdpClient;//发送用
        private const int port = 8001;//和本机绑定的端口号
        IPAddress ip;//本机ip
        IPAddress remoteip;//远程主机ip
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            //获取本机可用IP地址
            IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
            foreach (IPAddress ipa in ips)
            {
                if (ipa.AddressFamily == AddressFamily.InterNetwork)
                {
                    ip = ipa;
                    break;
                }
            }

            //为了在同一台机器调试,此IP也作为默认远程IP
            remoteip = ip;
            //IPAddress remoteip = IPAddress.Parse("");  
        }
        private void ReceiveData()
        {
            IPEndPoint local = new IPEndPoint(ip, port);
            receiveUdpClient = new UdpClient(local);
            IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
            while (true)
            {
                try
                {
                    //关闭udpClient 时此句会产生异常
                    byte[] receiveBytes = receiveUdpClient.Receive(ref remote);
                    string receiveMessage = Encoding.Unicode.GetString(
                        receiveBytes, 0, receiveBytes.Length);
                    listBox1.Items.Add("收到的消息:" + receiveMessage);
                }
                catch
                {
                    break;
                }
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            //创建一个线程接收远程主机发来的信息
            Thread myThread = new Thread(ReceiveData);
            myThread.IsBackground = true;
            myThread.Start();
        }
        private void SendMessage(object obj)
        {
            string message = (string)obj;
            sendUdpClient = new UdpClient(0);
            byte[] bytes = Encoding.UTF8.GetBytes(message);
            IPEndPoint iep = new IPEndPoint(remoteip, port);
            try
            {
                sendUdpClient.Send(bytes, bytes.Length, iep);
                listBox1.Items.Add("发送的消息:" + message);
                textBox1.Clear();
            }
            catch (Exception ex)
            {
                listBox1.Items.Add("发送出错:" + ex.Message);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //remoteip = IPAddress.Parse(txt_IPAddress.Text);
            Thread myThread = new Thread(SendMessage);
            myThread.IsBackground = true;
            myThread.Start(textBox1.Text);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        delegate void AddItemDelegate(ListBox listbox, string text);
        private void AddItem(ListBox listbox, string text)
        {
            if (listbox.InvokeRequired)
            {
                AddItemDelegate d = AddItem;
                //Control.Invoke 方法 (Delegate, Object[]):
                //在拥有控件的基础窗口句柄的线程上,用指定的参数列表执行指定委托。
                listbox.Invoke(d, new object[] { listbox, text });
            }
            else
            {
                //Add:动态的添加列表框中的项
                listbox.Items.Add(text);

                //SelectedIndex属性获取单项选择ListBox中当前选定项的位置
                //Count:列表框中条目的总数
                listbox.SelectedIndex = listbox.Items.Count - 1;

                //调用此方法等效于将 SelectedIndex 属性设置为-1。 
                //可以使用此方法快速取消选择列表中的所有项。
                listbox.ClearSelected();
            }
        }
        delegate void ClearTextBoxDelegate();
        private void ClearTextBox()
        {
            if (textBox1.InvokeRequired)
            {
                ClearTextBoxDelegate d = ClearTextBox;
                textBox1.Invoke(d);
            }
            else
            {
                textBox1.Clear();
                textBox1.Focus();
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}

点击运行,输入发送的信息:

在这里插入图片描述

点击发送之后:

在这里插入图片描述



打开wireshark,抓包以太网:(同一主机)

在这里插入图片描述

在这里插入图片描述



参考网址:


C#使用 UdpClient 类进行简单通信的例子



C#控制台编程及网络编程入门



版权声明:本文为weixin_47936384原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。