• C# WinForm UDP 发送和接收消息


    代码如下:

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    using System.Threading;
    using System.Windows.Forms;
    
    namespace WindowsFormsApp2
    {
        public partial class Form1 : Form
        {
            UdpClient client = new UdpClient();
            public Form1()
            {
                CheckForIllegalCrossThreadCalls = false;
                InitializeComponent();
                Thread recvThread = new Thread(RecvMsg);
                recvThread.IsBackground = true;
                recvThread.Start();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                string ip = textBox1.Text.Trim();
                string port = textBox2.Text.Trim();
                if (ip == null || port == null)
                {
                    return;
                }
                IPEndPoint host = new IPEndPoint(IPAddress.Parse(ip),Convert.ToInt32(port));
    
                client.Connect(host);
                richTextBox1.Text = "已连接\n";
                textBox1.Enabled = false;
                textBox2.Enabled = false;
                button1.Enabled = false;
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                if (client == null)
                {
                    return;
                }
                string content = richTextBox2.Text.Trim();
                if (content == "" || content == null)
                {
                    return;
                }
                byte[] buff = Encoding.UTF8.GetBytes(content);
                int v = client.Send(buff,buff.Length);
                richTextBox1.Text += content + "\n";
                richTextBox2.Text = null;
            }
    
            UdpClient recvClient = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.1.237"),40477));//接收方的IP
            private void RecvMsg()
            {
                while (1==1)
                {
                    IPEndPoint remoteHost = null;
                    byte[] recvByte = recvClient.Receive(ref remoteHost);
                    string msg = Encoding.UTF8.GetString(recvByte);
                    richTextBox1.Text += msg+"\n";
                }
            }
        }
    }
    

      界面以及结果:

     

  • 相关阅读:
    vue类似tab切换的效果,显示和隐藏的判断。
    vue 默认展开详情页
    vue echarts圆角阴影效果
    vue画图运用echarts
    随机函数rand()
    Qt解析CSV文件
    Qt生成CSV 文件
    QRegExp解析
    Qt中csv文件的导入与导出
    Qt 生成word、pdf文档
  • 原文地址:https://www.cnblogs.com/echo-lovely/p/14068037.html
Copyright © 2020-2023  润新知