zoukankan      html  css  js  c++  java
  • UDP server & client

    Server:

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    
    public class UDPServerTest {
    
        public static void main(String[] args) throws IOException {
            DatagramSocket ds = new DatagramSocket(9954);
    
            byte[] data = new byte[512];
            DatagramPacket dp = new DatagramPacket(data, data.length);
    
            while (true) {
                ds.receive(dp);
    
                System.out.println("receive:");
                System.out.println(dp.getSocketAddress());
                System.out.println(new String(data, "UTF-8"));
    
                //response
                String st = "qnmlgb~hi!";
                byte[] bytes = st.getBytes();
                DatagramPacket response = new DatagramPacket(bytes, bytes.length,
                    dp.getSocketAddress());
                ds.send(response);
            }
        }
    
    }

    Client:

    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetSocketAddress;
    
    public class UDPClientTest {
    
        public static InetSocketAddress localServer = new InetSocketAddress("127.0.0.1", 9954);
    
        public static void main(String[] args) throws IOException {
            DatagramSocket ds = new DatagramSocket();
            String st = "loull~hi!";
            byte[] data = st.getBytes();
            DatagramPacket dp = new DatagramPacket(data, data.length, localServer);
            ds.send(dp);
    
            int localPort = ds.getLocalPort();
            System.out.println("localport:" + localPort);
    
            byte[] buf = new byte[512];
            DatagramPacket receive = new DatagramPacket(buf, buf.length);
            ds.receive(receive);
            String response = new String(receive.getData(), 0, receive.getLength());
            System.out.println("response:" + response);
        }
    
    }
  • 相关阅读:
    django第10天(聚合查询,常用字段)
    django第9天(多表操作)
    django第8天(在测试文件中运行django项目|单表操作)
    django第七天(模板的复用性,include标签和母版)
    django第六天(模板相关,过滤器和标记)
    SparkCore2
    SparkCore
    SQL
    Spark基础
    使用Observer实现HBase到Elasticsearch的数据同步
  • 原文地址:https://www.cnblogs.com/549294286/p/5177322.html
Copyright © 2011-2022 走看看