Socket -- UdpClinet

UdpClient 类使用字节数组保存 UDP 数据文报。使用 Send 方法向网络发送数据,使用 Receive 方法接收传入的数据文报。

UdpClient 类提供了一些简单的方法,用于在阻止同步模式下发送和接收无连接 UDP 数据报。因为 UDP 是无连接传输协议,所以不需要在发送和接收数据前建立远程主机连接。但您可以选择使用下面两种方法之一来建立默认远程主机:

使用远程主机名和端口号作为参数创建 UdpClient 类的实例。

创建 UdpClient 类的实例,然后调用 Connect 方法。

可以使用在 UdpClient 中提供的任何一种发送方法将数据发送到远程设备。使用 Receive 方法可以从远程主机接收数据。

UdpClient 方法还允许发送和接收多路广播数据报。使用 JoinMulticastGroup 方法可以将 UdpClient 预订给多路广播组。使用 DropMulticastGroup 方法可以从多路广播组中取消对 UdpClient 的预订。

简例:
作为服务端:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace udpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建udpClient 绑定Ip跟端口号,,
            UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("192.168.1.11"), 3355));
            Console.WriteLine("创建UdpClient服务端");

            while (true)
            {
                //接收数据
                IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);
                //通过point确定数据来自哪个ip的端口号,返回值是一个字节数组,
                byte[] data = udpClient.Receive(ref point);
                string message = Encoding.UTF8.GetString(data);
                Console.WriteLine("收到了消息:" + message);
            }

            udpClient.Close();
            Console.ReadKey();
        }
    }
}

作为客户端:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace _004_udpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建UdpClient 绑定的端口号
            UdpClient udpclient = new UdpClient();
            Console.WriteLine("创建UdpClient客户端");

            while (true)
            {
                string message = Console.ReadLine();
                //将字符串转为数组
                byte[] data = Encoding.UTF8.GetBytes(message);
                //发送数据
                int length = udpclient.Send(data, data.Length, new IPEndPoint(IPAddress.Parse("192.168.1.11"), 3355));
            }

            udpclient.Close();
            Console.ReadKey();

        }
    }
}

udpClient

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

陈言必行

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

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

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

打赏作者

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

抵扣说明:

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

余额充值