• 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();
                }
            }
        }
    }
    
  • 相关阅读:
    GO语言面向对象06---面向对象练习01
    GO语言面向对象05---接口的多态
    GO语言面向对象04---接口的继承
    GO语言面向对象03---接口与断言
    GO语言面向对象02---继承
    Go语言练习---判断闰年以及根据现在的秒数求现在的年月日
    [操作系统] 线程管理
    [操作系统] 进程的状态
    [操作系统] 进程控制块
    关于这次计算机设计大赛
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10327705.html
Copyright © 2020-2023  润新知