zoukankan      html  css  js  c++  java
  • 【UDP 发送接收数据】

    package com.yjf.esupplier.common.test;
    
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    
    /**
     * @author shusheng
     * @description UDP 发送接收数据
     * @Email shusheng@yiji.com
     * @date 2019/1/6 0:21
     */
    public class SendDemo {
    
        public static void main(String[] args) throws Exception {
            DatagramSocket socket = new DatagramSocket();
            String str = "i love you";
            // 把数据进行封装到数据报包中
            DatagramPacket packet = new DatagramPacket(str.getBytes(),
                    str.length(), InetAddress.getByName("localhost"), 6666);
            socket.send(packet);// 发送
    
            byte[] buff = new byte[100];
            DatagramPacket packet2 = new DatagramPacket(buff, 100);
            socket.receive(packet2);
            System.out.println(new String(buff, 0, packet2.getLength()));
            socket.close();
        }
    
    }
    package com.yjf.esupplier.common.test;
    
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    
    /**
     * @author shusheng
     * @description UDP 发送接收数据
     * @Email shusheng@yiji.com
     * @date 2019/1/7 23:24
     */
    public class ReceiveDemo {
    
        public static void main(String[] args) throws Exception {
    
            // 先接收数据
            DatagramSocket socket = new DatagramSocket(6666);
            byte[] buff = new byte[100];
            DatagramPacket packet = new DatagramPacket(buff, buff.length);
            socket.receive(packet);// 接受传来的数据包
            System.out.println(new String(buff, 0, packet.getLength()));
    
            // 发送数据
            String str = "me too";
            DatagramPacket packet2 = new DatagramPacket(str.getBytes(),
                    str.length(), packet.getAddress(), packet.getPort());
            socket.send(packet2);
            socket.close();
        }
    
    }
    终身学习者
  • 相关阅读:
    CF 234 C Weather(粗暴方法)
    给工作赋予的新意义——Leo鉴书78
    获取集合的方法
    VS 统计代码行数
    , ,
    指针的删除动作
    C++ 名称空间
    boost::token_compress_on
    指针与引用
    容器的end()方法
  • 原文地址:https://www.cnblogs.com/zuixinxian/p/11275394.html
Copyright © 2011-2022 走看看