• C#网络编程之UDP


    UDP简介:UDP 是User Datagram Protocol的简称, 中文名是用户数据包协议,是一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务。UDP是与TCP相对应的协议,它是面向非连接的协议,它不与对方连接,而直接把数据包发送过去。“面向非连接”就是正式通信前不必与对方建立连接,不管对方状态就直接发送。

    UDP特性:

      (1)UDP是一个无连接协议,传输数据之前,源端和终端不建立连接,当它想传送时就简单的抓取来自应用程序的数据,并尽可能快的把他扔到网络上。在发送端UDP传送的速度仅仅是受应用程序数据生成的速度、计算机能力和传输带宽限制;在接收端,UDP把每个消息段放在队列中,应用程序每次从队列中读取一个消息段。

      (2)由于传输数据不建立连接,因此也就不需要维护连接状态,包括收发状态等,因此一台服务机可同时向多台客户机传输相同的信息。

      (3)UDP信息包的标题很短,只有8个字节,相对于TCP的20个字节信息包的额外开销很小。

      (4)吞吐量不受拥挤控制算法的调节,只受应用软件生成数据的速率、传输宽带、源端和终端主机性能的限制。

      (5)UDP使用尽量最大努力交付,即不保证可靠交付,因此主机不需要维持复杂的链接状态表(该表中有许多参数)。

      (6)UDP是面向报文的。发送方对应用程序交下来的报文,在添加首部后就向下交付个IP层。既不拆分,也不合并,而是保留这些报文的边界,因此,应用程序需要选择合适的报文大小。

    示例:在解决方案创建两个控制台程序:UDPSender,UDPReceive

    备注:

      (1)vs2012启动两个项目需设置:右键解决方案->通用属性->启动项目->多启动项目->勾选你要启动的多个项目->确定->启动

      (2)vs2012始终能看到解决方案的设置:工具->配置->项目和解决方案->常规->总是显示解决方案

      (3)IPEndPoint类包含应用程序连接到主机的服务所需的主机和本地或远程端口信息。通过组合服务的主机IP地址和端口号,IPEndPoint形成到服务的连接点。

    客户端:

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

    namespace UDPSender

    {

      class program

      {

      static void main(String[] args)

      {

        byte[] data = new byte[1024];

        string input,stringData;

        Console.WriteLine("this is a Client.host name is {0}",Dns.GetHostName());

        //设置服务器IP和端口号

        IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),8001);

        //定义网络类型,数据连接类型和网络协议UDP

        Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);

        string welcome = "Hello! I am a Client";

        data = Encoding.ASCII.GetBytes(welcome);

        server.SendTo(data,data.Length,SocketFlags.None,ipep);

        IPEndPoint sender = new IPEndPoint(IPAddress.Any,0);

        EndPoint Remote = (EndPoint)sender;

        data = new byte[1024];

        //对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制

        //server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 100);

        int recv = server.ReceiveFrom(data,ref Remote);

        Console.WriteLine("Message received from {0}: ", Remote.ToString());

        Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));

        while(true)

        {

          input = Console.ReadLine();

          if(input == "exit")

          {

            break;

          }

          server.SendTo(Encoding.ASCII.GetBytes(input),Remote);

          data = new byte[1024];

          recv = server.ReceiveFrom(data,ref Remote);

          stringData = Encoding.ASCII.GetString(data,0,recv);

          Console.WriteLine(stringData);

        }

      }

    }

    }

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

    namespace UDPReceive

    {

      class Program

      {

        static void main(String[] args)

        {

          int recv;

          byte[] data = new byte[1024];

          //得到本机IP,设置端口号

          IPEndPoint ipep = new IPEndPoint(IPAddress.Any,8001);

          Socket newsock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.UDP);

          //绑定网络地址

          newsock.Bind(ipep);

          Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName());

          //等待客户机连接

          Console.WriteLine("Waiting for a client");

          //得到客户端IP

          IPEndPoint sender= new IPEndPoint(IPAddress.Any,0);

          EndPoint Remote = (EndPoint)(sender);

          //接受数据

          recv = newsock.ReceiveFrom(data,ref Remote);

          Console.WriteLine("Message received from {0}",Remote.ToString());

          Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));

          //客户端连接成功后,发送信息

          string welcome = "Hi I am a Server";

          data = Encoding.ASCII.GetByte(welcome);

          //发送信息

          newsock.SendTo(data,data.Length,SocketFlags.None,Remote);

          while(true)

          {

            data = new byte[1024];

            //发送接受的信息

            recv = newsock.ReceiveFrom(data,ref Remote); 

            Console.WriteLine(Encoding.ASCII.GetString(data,0,recv));

            newsock.SendTo(data,recv,SocketFlags.None,Remote);

          }

        }

      }

    }

  • 相关阅读:
    [Swift]LeetCode895. 最大频率栈 | Maximum Frequency Stack
    [Swift]LeetCode894. 所有可能的满二叉树 | All Possible Full Binary Trees
    [Swift]LeetCode893. 特殊等价字符串组 | Groups of Special-Equivalent Strings
    [Swift]LeetCode892. 三维形体的表面积 | Surface Area of 3D Shapes
    [Swift]LeetCode891. 子序列宽度之和 | Sum of Subsequence Widths
    [Swift]LeetCode890. 查找和替换模式 | Find and Replace Pattern
    find missing conjunction, why?
    sh 脚本报错
    What's mean ORA-25191?
    饼状图
  • 原文地址:https://www.cnblogs.com/gnsds/p/3580130.html
Copyright © 2020-2023  润新知