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();
                }
            }
        }
    }
    
  • 相关阅读:
    oracle 的一点累积
    ZT: 网页的一些技巧
    ZT: WEB学习资料
    开源java
    倒序显示文本
    plsql使用之debug
    转 一些shell经验
    lpad rpad
    2018.8.19 2018暑假集训之maxnum
    2018.8.17 题解 2018暑假集训之编辑距离
  • 原文地址:https://www.cnblogs.com/xidian2014/p/10327705.html
Copyright © 2011-2022 走看看