C# UDP通讯(Socket和UdpClient)两种方式

本文介绍了使用C#进行UDP通信的两种方法:Socket和UdpClient。主要内容包括设置本地和远程IP及端口,发送数据到指定IP/Port,异步接收数据并判断来源,以及解决接收数据时可能出现的问题。同时提到了常见的错误及其修正方法。
摘要由CSDN通过智能技术生成

可分为两种:用C#本身的Socket或UdpClient;

1. udp通讯需指定两台机器的通讯IP和端口,即udp包发出机器的IP/Port和收到该包的IP/Port:

            this.localIp = IPAddress.Parse(localIp);
            this.remoteIp = IPAddress.Parse(remoteIp);
            this.remotePort = remotePort;
            this.localPort = localPort;

用socket时,需用Bind方法绑定本地IP和端口,即发出包的IP/Port:

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            socket.Bind(new IPEndPoint(this.localIp, this.localPort));

用UdpClient时,该绑定发出的socket方式已经写在UdpClient本身类中,构造时把本地IP和port传为参数:

            udpClient = new UdpClient(new IPEndPoint(this.localIp, this.localPort));

2. 发送数据:

            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.SetBuffer(data, 0, data.Length);
            args.RemoteEndPoint = new IPEndPoint(IPAddress.Parse(this.remoteIp.ToString()), this.remotePort);
            args.Completed += OnFireSendCompleted;
            socket.SendToAsync(args);     

            IPEndPoint remoteIpEP = new IPEndPoint(this.remoteIp, this.remotePort);
            udpClient.SendAsync(sendData, sendData.Length, remoteIpEP); 

即可将数据发送到另一台指定机器IP/Port

c#有IPEndPoint类可用来指定IP/Port

3. 接收数据:

3.1 均可实现异步接收包操作:

SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            var buff = new Byte[1024 * 100];
            args.SetBuffer(buff, 0, buff.Length);
            args.RemoteEndPoint = new DnsEndPoint(this.remoteIp.ToString(), this.remotePort);
            args.Completed += (sender, e) =>
            {
                    OnDataReceived(sender, e.Buffer);
            };
            socket.ReceiveAsync(args);

udpClient.ReceiveAsync();

3.2 接收数据后,当需要只响应特定IP/Port发来的数据时:

                 args.RemoteEndPoint = new DnsEndPoint(this.remoteIp.ToString(), this.remotePort);

                    IPEndPoint remoteEP = new IPEndPoint(this.remoteIp, this.remotePort);

                   UdpReceiveResult udpReceiveResult = await udpClient.ReceiveAsync();
                    if (udpReceiveResult.RemoteEndPoint.Equals(remoteEP))
                    {
               

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值