C# UDP通讯

  1. UDP不属于面向连接的通信,在选择协议时,选择UDP必须要谨慎。在网络质量较差情况下,UDP协议数据包丢失会比较严重。但是由于UDP的特性:它不属于连接型协议,具有资源消耗小,处理速度快等优点,所以通常音视频和普通数据在传送时使用UDP较多,因为它们即使偶尔丢失一两个数据包,也不会对接收结果产生太大影响。

  2. 通过UDP进行信息收发,并没有严格的客户端和服务端之分,它不同于TCP,TCP必须建立可靠连接之后才可以通信,而UDP随时都可以给指定的ip和端口所对应进程发送消息。

  3. UDP发送消息时需要绑定自己IP 和 端口号,接收消息的时候没有特殊限制,只要有人给自己发送,自己在线,就可以接收。

  4. 总之,使用UDP协议进行信息的传输之前不需要建立连接。换句话说就是客户端向服务器发送信息,客户端只需要给出服务器的ip地址和端口号,然后将信息封装到一个待发送的报文中并且发送出去。至于服务器端是否存在,或者能否收到该报文,客户端根本不用管。  

使用C#的socket实现UDP通信,代码如下:

1.Clicent客户端实现代码

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

namespace UdpClient
{
    class Program
    {
        static Socket client;
        static void Main(string[] args)
        {
            client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            client.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.101"), 8000));               //UDP通讯时,必须绑定自己的IP和端口号
            Thread threadSendMsg = new Thread(sendMsg); 
            threadSendMsg.Start();                          //开启发送消息线程
            Thread threadReciveMsg = new Thread(ReciveMsg);
            threadReciveMsg.Start();                        //开启接收消息线程
            Console.WriteLine("客户端已开启");
        }

        /// <summary>
        /// 向指定ip的主机端口发送数据报
        /// </summary>
        static void sendMsg()
        {
            EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 8001);
            while (true)
            {
                string msg = Console.ReadLine();//读取控制台窗口输入
                client.SendTo(Encoding.UTF8.GetBytes(msg), point);
            }
        }

        /// <summary>
        /// 接收发送给本机ip对应端口号的数据报
        /// </summary>
        static void ReciveMsg()
        {
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                byte[] buffer = new byte[1024];
                int length = client.ReceiveFrom(buffer, ref point);//接收数据报
                string message = Encoding.UTF8.GetString(buffer, 0, length);//将接收到的数据转换成字符串类型
                Console.WriteLine(DateTime.Now.ToString() + " Msg From: " + point.ToString() + ":" + message);//控制台打印出来
            }
        }
    }
}

2.Server服务端实现代码

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

namespace UdpServer
{
    class Program
    {
        static Socket server;
        static void Main(string[] args)
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            server.Bind(new IPEndPoint(IPAddress.Parse("192.168.1.101"), 8001));                //绑定端口号和IP
            Thread threadReciveMsg = new Thread(ReciveMsg);                                     //开启接收消息线程
            threadReciveMsg.Start();
            Thread threadSendMsg = new Thread(sendMsg);                                         //开启发送消息线程
            threadSendMsg.Start();
            Console.WriteLine("服务端已开启");
        }

        /// <summary>
        /// 向指定IP的主机端口发送数据报
        /// </summary>
        static void sendMsg()
        {
            EndPoint point = new IPEndPoint(IPAddress.Parse("192.168.1.101"), 8000);
            while (true)
            {
                string msg = Console.ReadLine();
                server.SendTo(Encoding.UTF8.GetBytes(msg), point);
            }
        }

        /// <summary>
        /// 接收发送给本机ip对应端口号的数据报
        /// </summary>
        static void ReciveMsg()
        {
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Any, 0);//用来保存发送方的ip和端口号
                byte[] buffer = new byte[1024];
                int length = server.ReceiveFrom(buffer, ref point);//接收数据报
                string message = Encoding.UTF8.GetString(buffer, 0, length);
                Console.WriteLine(DateTime.Now.ToString() + " Msg From: " + point.ToString() + ":" + message);
            }
        }
    }
}

  • 4
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值