1. 程式人生 > >Java實現簡單的聊天工具

Java實現簡單的聊天工具

先看程式碼:

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

public class Sender {
    private static DatagramSocket send; //套接字
    private static byte[] buff;    //緩衝區
    private static DatagramPacket packetReceived;  //接收的包
    private static InetAddress inetAddress;


    public Sender() throws Exception {
        buff = new byte[1024];
        packetReceived = new DatagramPacket(buff,buff.length);
        inetAddress = InetAddress.getByName("localhost");
        send = new DatagramSocket(5000);
    }

    private static String send() throws IOException {
        Scanner scan = new Scanner(System.in);
        //要傳送的資訊
        String str = scan.next();
        byte[] buff = str.getBytes();
        //資料報文
        DatagramPacket datagramPacket = new DatagramPacket(buff,buff.length,inetAddress,4000);
        //傳送
        send.send(datagramPacket);
        return str;
    }

    private static String receive() throws IOException {
        send.receive(packetReceived);
        String str = new String(packetReceived.getData(),0,packetReceived.getLength());
        return str;
    }

    public static void main(String[] args) throws Exception {
        Sender sender = new Sender();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    String msg = null;
                    try {
                        msg = send();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if(msg.equals("bye")){
                        send.close();
                        System.out.println("本次聊天結束");
                        System.exit(0);

                    }
                }
            }
        }.start(); //建立執行緒,呼叫start方法啟動執行緒
        new Thread(){
            @Override
            public void run() {
                while (true) {
                    String msg = null;
                    try {
                        msg = receive();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.printf("%s:%s\n",packetReceived.getAddress().getHostAddress(),msg);
                    if(msg.equals("bye")){
                        send.close();
                        System.out.println("本次聊天結束");
                        System.exit(0);
                    }
                }
            }
        }.start();
    }
}

 這實現了一個簡單的聊天聊天工具,當然僅平這一個類還是不夠的,如果是打算在自己電腦上實現兩天,則需要在寫一個類,程式碼跟這個一模一樣,改改類名就好,然後執行兩個類,就可以互發資訊了.如果想在兩臺電腦之間通訊,就需要在另一臺電腦上也寫上程式碼,然後將inetAddress = InetAddress.getByName("localhost");裡面的localhost改成對方的ip地址,注意兩臺電腦須在同意區域網下,方可通訊