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);
        }
    
    }
  • 相关阅读:
    解决Eclipse中文乱码
    C++中set用法回顾
    二分查找题目汇总
    给网卡配置多个IP地址(win/linux)
    route在windows与liunx下的使用区别
    eclipse 编程 c++ 快捷键
    Git、GitHub、GitLab三者之间的联系以及区别
    SQL语句优化
    《领域驱动设计的原则与实践》读书笔记(一)
    DotNet Core 介绍
  • 原文地址:https://www.cnblogs.com/549294286/p/5177322.html
Copyright © 2011-2022 走看看