C#winform UDP通信 发送和接收信息

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 UDP测试_客户端
{
    public partial class ClientForm2 : Form
    {
        public ClientForm2()
        {
            InitializeComponent();
        }
        static Socket client;
        Thread t;
        Thread t2;
        string recv;
        private void btnSend_Click(object sender, EventArgs e)
        {
            EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.48.1"), 6001);
            string msg = txtSend.Text;
            client.SendTo(Encoding.UTF8.GetBytes(msg), point);
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            txtReciv.Text = recv ;
        }

        private void ClientForm2_Load(object sender, EventArgs e)
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            client.Bind(new IPEndPoint(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text)));

            t = new Thread(sendMsg);
            //t.Start();

            t2 = new Thread(ReciveMsg);
            t2.Start();

            timer1.Start();
        }
        /// <summary>
        /// 向特定ip的主机的端口发送数据报
        /// </summary>
        void sendMsg()
        {
            EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.48.1"), 6001);
            while (true)
            {
                string msg = txtSend.Text;
                client.SendTo(Encoding.Default.GetBytes(msg), point);
            }
        }
        /// <summary>
        /// 接收发送给本机ip对应端口号的数据报
        /// </summary>
        void ReciveMsg()
        {
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                byte[] buffer = new byte[1024];
                int length = client.ReceiveFrom(buffer, ref point);//接收数据报
                recv += Encoding.UTF8.GetString(buffer, 0, length);
                recv += "\r\n";
                //txtReciv.Text += recv;
            }
        }

        private void ClientForm2_FormClosing(object sender, FormClosingEventArgs e)
        {
            timer1.Stop();
            t.Abort();
            t2.Abort();
        }
    }
}
         UDP通信不需要建立连接。
  • 6
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Big_潘大师

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

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

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

打赏作者

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

抵扣说明:

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

余额充值