万金流
初次使用博客园,目前感觉还不错。 不知不觉用了4年零4个月了,越来越喜欢博客园。

跟tcpclient类似。

不同之处:1、udp没有稳定通道,所有内容需要用字节形式收发。2、udpclient的connect方法,仅指定默认的发送目的地,并没有连接动作。

最简的代码如下:

被连接端:

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            UdpClient udp = new UdpClient(9000);//ipv6:new UdpClient:9000,AddressFamily.InterNetworkV6);
            string msg;
            IPEndPoint iPEndPoint = new IPEndPoint(IPAddress.Any, 0);//ipv6:IPAddress.IPv6Any
            do
            {
                msg = Encoding.Unicode.GetString(udp.Receive(ref iPEndPoint));
                Console.WriteLine($"{iPEndPoint}:{msg}");
            } while (msg.ToLower() != "exit");
            Console.ReadKey();
        }
    }
}

连接端:

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

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            //可以使用不同的构造方法指定本地ip端口。
            UdpClient udp = new UdpClient();//ipv6:new UdpClient(AddressFamily.InterNetworkV6);
            string msg;
            byte[] b_msg;
            udp.Connect(IPAddress.Parse("127.0.0.1"), 9000);
            do
            {
                msg = Console.ReadLine();
                b_msg = Encoding.Unicode.GetBytes(msg);
                udp.Send(b_msg, b_msg.Length);
            } while (msg.ToLower() != "exit");
            Console.ReadKey();
        }
    }
}

运行结果:

 

 可以以此为蓝本,仿照tcpclient的方式,完成双向通讯和聊天室程序。

经实测,目标ip地址更换为广播地址

IPAddress.Broadcast

后,即可实现广播消息发送。

posted on 2020-06-01 18:09  万金流  阅读(839)  评论(0编辑  收藏  举报