C# 34. UdpClient收发

//UdpClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Xxxxx
{
    class UdpClient
    {
        private Socket client;
        private string strIp;
        private int port;
        private byte[] msg;

        public void UdpClientSocketCreat(string strIp,int port)
        {
            //创建客户端
            client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPAddress ip = IPAddress.Parse(strIp);
            ///端口号
            IPEndPoint endPoint = new IPEndPoint(ip, port);
            ///建立与服务器的远程连接
            client.Connect(endPoint);
            ///线程问题
            Thread thread = new Thread(ReciveMsg);
            thread.IsBackground = true;
            thread.Start(client);
            Console.WriteLine("客户端已成功开启!");
        }

        //向特定ip的主机的端口发送数据
        void SendMsg()
        {
            //获取IP与端口号
            EndPoint point = new IPEndPoint(IPAddress.Parse(strIp), port);
            //将数据发送到指定的ip的主机的端口
            client.SendTo(msg, point);
        }

        public void Send(string strIp, int port, byte[] msg)
        {
            this.strIp = strIp;
            this.port = port;
            this.msg = msg;
            //开启发送消息线程
            Thread t1 = new Thread(SendMsg);
            t1.Start();
        }
        //接收发送给本机ip对应端口号的数据
        void ReciveMsg(object o)
        {
            Socket client = o as Socket;
            while (true)
            {
                try
                {
                    ///用来保存发送方的ip和端口号
                    EndPoint point = new IPEndPoint(IPAddress.Any, 0);
                    ///定义客户端接收到的信息大小
                    byte[] buffer = new byte[2000];
                    ///接收到的信息大小(所占字节数)
                    int length = client.Receive(buffer);

                }
                catch (Exception)
                {
                    client.Close();
                }
            }
        }
    }
}
//使用
UdpClient udpClient = new UdpClient();
byte[] buf = {0x01,0x02,0x03,0x04,0x05};
udpClient.Send("192.168.90.100",3456, buf);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值