• java,UDP协议简单实现


    //UDP协议简单实现-----Server
    package
    UDP; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.nio.ByteBuffer; public class UdpServer implements Runnable { private int port; public UdpServer(int port) { this.port = port; } public void run() { try { // listening at port for udp request DatagramSocket server = new DatagramSocket(new InetSocketAddress(port)); byte[] bs = new byte[4]; ByteBuffer bbuf = null; DatagramPacket data = new DatagramPacket(bs, bs.length); server.setSoTimeout(1000 * 10); // set timeout while (true) { // 一直监听 server.receive(data); bbuf = ByteBuffer.wrap(bs, 0, 4); String s = "receive " + data.getData().length + " byte data,value: " + bbuf.getInt(); System.out.println(s); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { new Thread(new UdpServer(11111)).start(); } }

    //客户端实现;

    package UDP;
    
        import java.net.DatagramPacket;
        import java.net.DatagramSocket;
        import java.net.InetSocketAddress;
    
    
        public class UdpClient implements Runnable {
            private int port;
    
            public UdpClient(int port) {
                this.port = port;
            }
    
            public void run() {
                try {
                    DatagramSocket client = new DatagramSocket();
                    byte[] bs = new byte[4];
                    InetSocketAddress isa = new InetSocketAddress("localhost", port);
                    DatagramPacket data = new DatagramPacket(bs, bs.length);
                    data.setSocketAddress(isa);
                    for (int i = 0; i < 10; i++) {
                        data.setData(int2bytes(i));
                        client.send(data);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    
            static byte[] int2bytes(int num) {
                byte[] b = new byte[4];
                for (int i = 0; i < 4; i++) {
                    b[i] = (byte) (num >>> (24 - i * 8));
                }
                return b;
            }
        }

    //测试代码;

    package UDP;
    
    public class Test {
        public static void main(String[] args) throws InterruptedException {
            int port = 11111;
            try{
                new Thread(new UdpServer(port)).start();
                new Thread(new UdpClient(port)).start();
            }catch(Exception e){
                //e.printStackTrace();
            }
        }
    }
  • 相关阅读:
    关于float和double类型能表示的数据范围和精度分析
    P2737 [USACO4.1]麦香牛块Beef McNuggets 数学题 + 放缩思想
    csu 1554: SG Value 思维题
    csu 1551: Longest Increasing Subsequence Again BIT + 思维
    Rasheda And The Zeriba Gym
    cpc,a wonderful concert
    hdu_3308 区间合并
    poj_3667线段树区间合并
    poj_2777线段树+位运算
    poj_3468,线段树成段更新
  • 原文地址:https://www.cnblogs.com/qianyukun/p/4308785.html
Copyright © 2020-2023  润新知