zoukankan      html  css  js  c++  java
  • Socket/UDP/TCP学习笔记

    1.UDP发送步骤

      1)建立UDP socket服务(通过DatagramSocket对象)
      2)提供数据,并交数据封装到数据包中(通过DatagramPacket对象)
      3)通过socket服务的发送功能,将数据包发送出去ds.send(dp);
      4)关闭资源

    View Code
        
        public static void main(String[] args) throws IOException {
            //1 创建UDP服务,通过DatagramSocket对象
            DatagramSocket ds = new DatagramSocket();
            //2. 确定数据,并封装成数据包。DatagramPacket(byte[] buf, int len,InetAddress add,int port);
            byte[] buf = "UDP MSG".getBytes();
            //add是发送目的地的IP,port是发送目的应用程序的端口号
            DatagramPacket dp = 
                    new DatagramPacket(buf, buf.length, InetAddress.getByName("192.168.1.254"),10000);
            //3.通过socket服务,将已有的数据包发送出去
            ds.send(dp);
            //4.关闭资源
            ds.close();
        }
    
    }

     2.UDP接收步骤

      1)定义UDP socket服务。通常会监听一个端口(DatagramSocket(int port))。方便于明确哪些数据过来该应用程序要处理。

      2)定义一个数据包。存储接收到的数据(DatagramPacket(byte[] data, int len))

      3)通过socket服务的receive方法,将收到的数据存入已定义好的数据包中。

      4)通过数据包对象的特有功能,将这些不同的数据取出。

      5)关闭资源

    View Code
    public class UDPReceive {
    
        public static void main(String[] args) throws Exception {
            //1.创建UDP socket,并把端口号10000绑定给这个应用程序
            DatagramSocket ds = new DatagramSocket(10000);
            while(true){
                //2.定义数据包,用于存储数据
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf, buf.length);
                //3.通过服务的receive方法将数据存入到数据包中
                ds.receive(dp);
                //4.通过数据包的方法,获取其中的数据。
                String ip = dp.getAddress().getHostAddress();//发送端的IP地址
                String data = new String(dp.getData(), 0, dp.getLength());
                int port = dp.getPort();//发送端的端口号
                System.out.println("received data");
                System.out.println(ip + "::" + data + "::" + port);
                //5.关闭资源
                //ds.close();
            }
        }
    }

    注:运行UDPReceive.java进行监听,这样UDP发送的消息才能收到。

         如果UDPsend,假设是A发送的IP是192.168.255,这是一个广播地址,如果这个广播地址绑定端口(假设10001),只要这个IP段内,有人开UDPReceive,监听10001,便能收到A的信息。

  • 相关阅读:
    oracle 数据库服务名怎么查
    vmware vsphere 6.5
    vSphere虚拟化之ESXi的安装及部署
    ArcMap中无法添加ArcGIS Online底图的诊断方法
    ArcGIS中字段计算器(高级计算VBScript、Python)
    Bad habits : Putting NOLOCK everywhere
    Understanding the Impact of NOLOCK and WITH NOLOCK Table Hints in SQL Server
    with(nolock) or (nolock)
    What is “with (nolock)” in SQL Server?
    Changing SQL Server Collation After Installation
  • 原文地址:https://www.cnblogs.com/baron89/p/3067987.html
Copyright © 2011-2022 走看看