天天看點

簡單模拟聊天

伺服器端:代碼展示

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket();   //建立伺服器端口号
        ExecutorService service = Executors.newCachedThreadPool();  //建立線程池
        ConcurrentHashMap<Socket, SocketAddress> hashMap = new ConcurrentHashMap<>();
        System.out.println("等待伺服器連接配接。。。");
        while (true) {
            Socket accept = ss.accept();
            hashMap.put(accept, accept.getRemoteSocketAddress());//等待用戶端連接配接
            service.submit(() -> {          //把所要執行的代碼放到線程池中執行
                try {
                    byte[] bytes = new byte[];        //建立位元組數組
                    InputStream inputStream = accept.getInputStream();//伺服器讀入用戶端所傳來的資訊
                    SocketAddress address = accept.getRemoteSocketAddress();
                    while (true) {
                        int read = inputStream.read(bytes); //把讀入的資訊放到位元組數組中
                        if (read == -) {      //如果讀到-1則結束讀的過程
                            break;
                        }
                        String s = address + "" + new String(bytes, , read);  //把讀入位元組數組的資訊轉化成字元串并且列印出來
                        //System.out.println(s);
                        for (Socket sd : hashMap.keySet()) {
                            OutputStream outputStream = sd.getOutputStream();
                            outputStream.write(s.getBytes());
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

            });
        }

    }
}
           

用戶端:代碼展示:

public class Demo {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", );   //建立用戶端
        Scanner sc = new Scanner(System.in);    //建立輸入流
        new Thread(() -> {
            InputStream inputStream = null;
            try {
                inputStream = socket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (true) {
                byte[] bytes = new byte[];
                int read = ;
                try {
                    read = inputStream.read(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (read == -) {
                    break;
                }
                String string = new String(bytes, , read);
                System.out.println(string);

            }
        }).start();
        while (true) {
            String s = sc.nextLine();       //從控制台輸入,并且發送給伺服器端
            socket.getOutputStream().write(s.getBytes());
        }
    }
}