C# 使用UDP进行网络通信

       在选择使用协议的时候,选择UDP必须要谨慎。在网络质量令人十分不满意的环境下,UDP协议数据包丢失会比较严重。但是由于UDP的特性:它不属于连接型协议,因而具有资源消耗小,处理速度快的优点,所以通常音频、视频和普通数据在传送时使用UDP较多,因为它们即使偶尔丢失一两个数据包,也不会对接收结果产生太大影响。比如我们聊天用的ICQ和QQ就是使用的UDP协议。

服务端代码

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服务器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            textBox1.Text = "127.0.0.1";
            textBox2.Text = "8401";
        }
        /// <summary>
        /// 获取本地IP
        /// </summary>
        private void label1_Click(object sender, EventArgs e)
        {
            string ip = IPAddress.Any.ToString();
            textBox1.Text = ip;
        }

        Socket server;
        private void button2_Click(object sender, EventArgs e)
        {

            server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            server.Bind(new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text)));//绑定端口号和IP
            //server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
            listBox1.Items.Add("服务器已经成功开启!");
            //开启接收消息线程
            Thread t = new Thread(ReciveMsg);
            t.IsBackground = true;
            t.Start();
        }
        /// <summary>
        /// 向特定ip的主机的端口发送数据
        /// </summary>te
        void SendMsg()
        {
            EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8400);    //向指定的IP和端口发送消息
            string msg = textBox3.Text;
            server.SendTo(Encoding.UTF8.GetBytes(msg), point);
        }


        /// <summary>
        /// 接收发送给本机ip对应端口号的数据
        /// </summary>
        void ReciveMsg()
        {
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                byte[] buffer = new byte[1024 * 1024];
                int length = server.ReceiveFrom(buffer, ref point);//接收数据报
                string message = Encoding.UTF8.GetString(buffer, 0, length);
                listBox1.Items.Add(point.ToString() + ":" + message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox3.Text != "")
            {
                //开启发送消息线程
                Thread t3 = new Thread(SendMsg);
                t3.Start();
                listBox1.Items.Add(textBox1.Text + ":" + textBox2.Text + ":" + textBox3.Text);
            }


        }


    }
}

客户端代码

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客户端
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            CheckForIllegalCrossThreadCalls = false;
            InitializeComponent();
            textBox1.Text = "127.0.0.1";
            textBox2.Text = "8400";
        }
        /// <summary>
        /// 创建客户端
        /// </summary>
        Socket client;

        private void button2_Click(object sender, EventArgs e)
        {
            
           

            ///创建客户端
            client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            client.Bind(new IPEndPoint(IPAddress.Parse(textBox1.Text), int.Parse(textBox2.Text)));
            ///线程问题
            Thread thread = new Thread(ReciveMsg);
            thread.IsBackground = true;
            thread.Start(client);
            listBox1.Items.Add("客户端已成功开启!");
        }

        /// <summary>
        /// 向特定ip的主机的端口发送数据
        /// </summary>
        void SendMsg()
        {
            EndPoint point = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8401);    //向指定的IP和端口发送消息
            ///发送内容
            string msg = textBox3.Text;
            ///将数据发送到指定的ip的主机的端口
            client.SendTo(Encoding.UTF8.GetBytes(msg), point);
        }
        /// <summary>
        /// 接收发送给本机ip对应端口号的数据
        /// </summary>
        void ReciveMsg(object o)
        {

            while (true)
            {
                try
                {
                    ///用来保存发送方的ip和端口号
                    EndPoint point = new IPEndPoint(IPAddress.Any, 0);
                    //MessageBox.Show(point.ToString());
                    ///定义客户端接收到的信息大小
                    byte[] buffer = new byte[1024 * 1024];
                    ///接收到的信息大小(所占字节数)
                    int length = client.ReceiveFrom(buffer, ref point);
                    string message = Encoding.UTF8.GetString(buffer, 0, length);
                    listBox1.Items.Add(point.ToString() + ":" + message);
                }
                catch (Exception)
                {
                    client.Close();
                }

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox3.Text != "")
            {
                //开启发送消息线程
                Thread t2 = new Thread(SendMsg);
                t2.Start();
                listBox1.Items.Add(textBox1.Text + ":" + textBox2.Text + ":" + textBox3.Text);
            }

        }
    }
}

效果展示

代码下载地址:

链接:https://pan.baidu.com/s/1r-V80I5fJ-8noF8YgMOlLA 
提取码:qx3s

  • 17
    点赞
  • 75
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
使用UDP进行Python和C#之间的通信时,你需要在两个应用程序中分别实现UDP的发送和接收功能。下面是一个简单的示例代码,演示了Python和C#之间通过UDP进行通信的过程。 Python端代码(发送端): ```python import socket def main(): target_ip = "192.168.1.100" # 目标IP地址 target_port = 1111 # 目标端口号 # 创建UDP套接字 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) while True: message = input("请输入要发送的消息:") if message == "exit": break # 发送消息到目标IP和端口 sock.sendto(message.encode(), (target_ip, target_port)) sock.close() if __name__ == '__main__': main() ``` C#端代码(接收端): ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace udp_server { class Program { static int port = 1111; // 接收端口号 static void Main(string[] args) { Console.WriteLine("服务器启动....."); // 创建UDP套接字 UdpClient udpClient = new UdpClient(port); IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, port); while (true) { // 接收消息 byte[] bytes = udpClient.Receive(ref remoteEP); string message = Encoding.UTF8.GetString(bytes); Console.WriteLine("接收到消息:" + message); } udpClient.Close(); } } } ``` 这个示例中,Python端通过创建UDP套接字,然后从用户输入读取消息,并将消息发送到指定的目标IP和端口。C#端通过创建UDP套接字,然后循环接收来自Python端发送的消息,并在控制台显示接收到的消息。 注意:在实际使用中,你需要根据具体的网络配置和需求进行适当的调整和处理。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哦呵呵呵呵嗝~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值