zoukankan      html  css  js  c++  java
  • 网络编程之udpclient简单使用

    首先写个接受消息的服务端(接收方一般定义为服务端,发送方一般定义为客户端)。这里偷了点懒,new UdpClient(11000)就是用Udp方式侦听11000端口,侦听任何发送到11000端口的消息都会接收到。

                      static void Main(string[] args)
            {
                UdpClient udpClient = new UdpClient(11000);
                try
                {
                    while (true)
                       
                   {
                        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);//字节数组(二进制),而不是流形式数据
                        string returnData = Encoding.ASCII.GetString(receiveBytes);
                        Console.WriteLine("This is the message you received " + returnData.ToString());
                        Console.WriteLine("This message was sent from " + RemoteIpEndPoint.Address.ToString() + " on their port number " + RemoteIpEndPoint.Port.ToString());
                     //   udpClient.Close();
                        Console.Read();
                    }
                }
                catch (Exception e)
                { Console.WriteLine(e.ToString()); }
            }

    然后写个发udp的客户端:

       static void Main(string[] args)
            {
                UdpClient udpClient = new UdpClient(11001);
                try
                {
                    udpClient.Connect(IPAddress.Parse("192.168.1.255"), 11000); //但是udp是无连接协议
                 //   udpClient.Connect("localhost", 11000);也可以使用这个连接方式
                    Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody thereA?");
                    udpClient.Send(sendBytes, sendBytes.Length); udpClient.Close();
                }
                catch  (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }

            }

    其中192.168.1.255是你的内网广播地址,也可以使用你的本机地址,11000是客户端的端口。

    广播地址是通过你的子网掩码获得的例如你的网关是192.168.0.1,掩码是255.255.255.0,那么你的广播地址就是192.168.0.255.

  • 相关阅读:
    POJ 2187 Beauty Contest(凸包+旋转卡壳)
    POJ 3845 Fractal(计算几何の旋转缩放)
    POJ 1755 Triathlon(线性规划の半平面交)
    POJ 2540 Hotter Colder(半平面交)
    POJ 3525/UVA 1396 Most Distant Point from the Sea(二分+半平面交)
    POJ 3348 Cows(凸包+多边形面积)
    POJ 1228 Grandpa's Estate(凸包唯一性判断)
    POJ 2826 An Easy Problem?!(线段交点+简单计算)
    如何在ARC代码中混编非ARC代码
    给view 添加事件
  • 原文地址:https://www.cnblogs.com/hedongnan/p/3141430.html
Copyright © 2011-2022 走看看