1. 程式人生 > 其它 >java網路程式設計初識

java網路程式設計初識

多人線上聊天基於(UDP)

傳送端

public class TalkSend implements Runnable {


    DatagramSocket socket = null;
    BufferedReader reader = null;

    private int fromPort;
    private String toIp;
    private int toPort;

    public TalkSend(int fromPort, String toIp, int toPort) {
        this.fromPort = fromPort;
        this.toIp = toIp;
        this.toPort = toPort;
        try {
            socket = new DatagramSocket(fromPort);
            reader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    @Override
    public void run() {
        while (true) {
            try {
                String data = reader.readLine();
                byte[] datas = data.getBytes(StandardCharsets.UTF_8);
                DatagramPacket packet = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress(this.toIp, this.toPort));

                socket.send(packet);
                if (data.equals("bye")) {
                    break;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        socket.close();
    }
}

接受端

public class TalkRecevive implements Runnable {


    DatagramSocket socket = null;
    private int port;
    private String msgFrom;

    public TalkRecevive(int port, String msFrom) {
        this.port = port;
        this.msgFrom = msFrom;
        try {
            socket = new DatagramSocket(port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void run() {
        while (true) {
            try {
                byte[] container = new byte[1024];
                DatagramPacket packet = new DatagramPacket(container, 0, container.length);
                socket.receive(packet); //阻塞式接受包裹

                byte[] data = packet.getData();
                String receiveData = new String(data, 0, data.length);
                System.out.println(msgFrom + ": " + receiveData);

                if (receiveData.equals("bye")) {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }


        }
        socket.close();
    }
}

使用者

學生角色

public class TalkStudent {
    public static void main(String[] args) {
        //開啟兩個執行緒
        new Thread(new TalkSend(7777,"localhost",9999)).start();
        new Thread(new TalkRecevive(8888,"老師")).start();

    }
}

老師角色

public class TalkTeacher {
    public static void main(String[] args) {
        new Thread(new TalkSend(5555,"localhost",8888)).start();
        new Thread(new TalkRecevive(9999,"學生")).start();
    }
}