Java UDP编程实例

总序

在学习UDP的编程 虽然可能在实际项目上用不到,但是并不影响我学习。由于时间原因 先贴出代码,后续的解释在未来修改添加

  • UDP客户端
  • UDP服务器端

    UDP客户端

package UDPTest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created by bamboo on 2016/6/28.
 */
public class UdpPoke {
    private int bufferSize;//单位字节
    private int timeout;//单位ms
    private InetAddress host;
    private int port;

    public UdpPoke(int bufferSize, int timeout, InetAddress inetAddress, int port) {
        this.bufferSize = bufferSize;
        this.host = inetAddress;
        if (port < 1 || port > 65535) {
            throw new IllegalArgumentException("端口out of range");
        }
        this.port = port;
        this.timeout = timeout;
    }

    public UdpPoke(InetAddress inetAddress, int port) {
        this(8192, 30000, inetAddress, port);
    }

    public UdpPoke(int bufferSize, InetAddress inetAddress, int port) {
        this(bufferSize, 30000, inetAddress, port);
    }

    /**
     *
     * @return 返回从服务器端收到来的字节数组
     */
    public byte[] poke() {
        //0表示随机一个可用的端口 一个随机的socket端口,用来与服务器做连接
        try (DatagramSocket datagramSocket = new DatagramSocket(0)) {
            //要发送的数据,简短一点,为了测试是否成功
            String a = new String("try to test");
            //输出packet 数据报
            DatagramPacket outgoing = new DatagramPacket(a.getBytes(), a.length(), host, port);
            //由客户端发起的连接
            datagramSocket.connect(host, port);
            datagramSocket.setSoTimeout(timeout);
            //发送数据报
            datagramSocket.send(outgoing);
            //
            DatagramPacket incoming = new DatagramPacket(new byte[bufferSize], bufferSize);
            //此处会阻塞,。直到从socket中收取到数据
            datagramSocket.receive(incoming);
            //数据解析并打印
            int readLength = incoming.getLength();
            byte[] response = new byte[readLength];
            System.arraycopy(incoming.getData(), 0, response, 0, readLength);
            return response;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        InetAddress host;
        int port;
        try {
            host = InetAddress.getByName("localhost");
            port = 1500;
            UdpPoke poker = new UdpPoke(host, port);
            byte[] response = poker.poke();
            if (response == null) {
                System.out.println("没有收到数据");
                return;
            }
            String result = new String(response);
            System.out.println("从服务器收到的数据为"+result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

UDP服务器端

UDP服务器抽象类

package UDPTest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Created by bamboo on 2016/6/28.
 */

/**
 * 对于服务器而言,是先收到数据,然后做回应
 * 对于回应,应当交由子类实现更好
 */
public abstract class UdpServer implements Runnable {
    private int bufferSize;
    private int port;
    private volatile boolean isShutDown = false;

    @Override
    public void run() {
        byte[] buffer = new byte[bufferSize];
        try (DatagramSocket socket = new DatagramSocket(port)) {
            socket.setSoTimeout(30000);
            while (true) {
                if (isShutDown) return;
                //先收
                DatagramPacket incoming = new DatagramPacket(buffer, 0, bufferSize);
                try {
                    //收取数据
                    socket.receive(incoming);
                    //数据处理以及回应
                    this.respond(socket, incoming);
                } catch (IOException e) {
                    if (isShutDown) return;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public abstract void respond(DatagramSocket socket, DatagramPacket incoming) throws IOException;


    public UdpServer(int port, int bufferSize) {
        this.bufferSize = bufferSize;
        this.port = port;
    }

    public UdpServer(int port) {
        this(port, 8192);
    }


}

UDP服务器实现类

package UDPTest;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Created by bamboo on 2016/6/28.
 */
public class UdpEchoServer extends UdpServer {
    private static final int DEFAULT_PORT = 1500;

    public UdpEchoServer() {
        super(DEFAULT_PORT);
    }

    @Override
    public void run() {
        super.run();
    }

    @Override
    public void respond(DatagramSocket socket, DatagramPacket incoming) throws IOException {
        DatagramPacket outgoing = new DatagramPacket(incoming.getData(),
                incoming.getLength(), incoming.getAddress(), incoming.getPort());
        socket.send(outgoing);
    }

    public static void main(String[] args) {
        Thread t = new Thread(new UdpEchoServer());
        t.start();
    }
}

编译运行

  1. 先运行服务器端 java UdpEchoServer
  2. 运行客户端 java UdpPoke

效果;
这里写图片描述

你可能感兴趣的:(Java)