• 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 = "已连接
    ";
                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 + "
    ";
                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+"
    ";
                }
            }
        }
    }
    

      界面以及结果:

     

  • 相关阅读:
    the address of vector
    C++ templete: "class" vs "typename" in a templateparameter
    [C++]Template Argument Deduction: automatic type conversation is not allowed
    C++0x learning: Sequencing rules of assignment.
    Good book for C++
    [C/C++]Switch比if else快.
    operator int*() vs int* operator ()()
    UML类图
    android中shape的使用(android:angle小解)
    Activity的Launch mode详解 singleTask正解
  • 原文地址:https://www.cnblogs.com/FlyonGrass/p/14068037.html
Copyright © 2020-2023  润新知