zoukankan      html  css  js  c++  java
  • UDP

    package com.test;
    
    import org.junit.Test;
    
    import java.io.IOException;
    import java.net.DatagramPacket;
    import java.net.DatagramSocket;
    import java.net.InetAddress;
    import java.net.SocketException;
    
    public class TestUDP {
        @Test
        public void client() {
            DatagramSocket ds = null;
            try {
                ds = new DatagramSocket();
    
                String data = "hellow udpserver";
                DatagramPacket dp = new DatagramPacket(data.getBytes(),
                        data.length(), InetAddress.getLocalHost(),
                        666
                );
                ds.send(dp);
    
                byte[] buf = new byte[1024];
                DatagramPacket dpIn = new DatagramPacket(buf, buf.length);
                ds.receive(dpIn);
                System.out.println(new String(dpIn.getData(), 0, dpIn.getLength()));
    
                ds.close();
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ds != null) {
                    ds.close();
                }
            }
        }
    
        @Test
        public void server() {
            DatagramSocket ds = null;
            try {
                ds = new DatagramSocket(666);
                byte[] buf = new byte[1024];
                DatagramPacket dp = new DatagramPacket(buf, buf.length);
                ds.receive(dp);
    
                byte[] data = dp.getData();
                int length = dp.getLength();
                InetAddress ipClient = dp.getAddress();
                int port = dp.getPort();
    
                String str = new String(data, 0, length);
                System.out.println("Server received:" + str);
    
                String dataout = "hellow udpClient, i have received";
                DatagramPacket dpout = new DatagramPacket(dataout.getBytes(), dataout.length(), ipClient, port);
                ds.send(dpout);
    
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ds != null) {
                    ds.close();
                }
            }
        }
    }
    
  • 相关阅读:
    系统优化怎么做-JVM优化之开篇
    系统优化怎么做-Tomcat优化
    系统优化怎么做-Linux系统配置优化
    系统优化怎么做-SQL优化
    系统优化怎么做-数据库优化
    系统优化怎么做-新系统上线前做什么
    系统优化怎么做-开篇
    一起学习Avalonia(一)
    etcd的应用举例
    c#总结几种正则表达式使用
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10327705.html
Copyright © 2011-2022 走看看