第一章:KVM概述
阿新 • • 發佈:2022-05-12
客戶端
public class Client { public static void main(String[] args) { // 服務端地址和埠 final String DEFAULT_SERVER_HOST = "127.0.0.1"; final Integer DEFAULT_SERVER_PORT = 8888; Socket socket = null; try { // 建立socket socket = new Socket(DEFAULT_SERVER_HOST, DEFAULT_SERVER_PORT);// 接收訊息 BufferedReader buffReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 傳送訊息 BufferedWriter buffWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); String msg = null; // 獲取使用者輸入的訊息 BufferedReader userReader = newBufferedReader(new InputStreamReader(System.in)); while (true) { String input = userReader.readLine(); // 寫入客戶端要傳送的訊息。因為服務端用readLine獲取訊息,其以\n為終點,所以要在訊息最後加上\n buffWriter.write(input + "\n"); // 重新整理快取 buffWriter.flush();// 讀取服務端資訊 msg = buffReader.readLine(); System.out.println(msg); // 如果客戶端輸入quit就可以跳出迴圈、斷開連線了 if (input.equals("quit")) { break; } } socket.close(); } catch (IOException e) { e.printStackTrace(); } } }
服務端
public class Server { public static void main(String[] args) { // 監聽8888埠 final int DEFAULT_PORT = 8888; ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(DEFAULT_PORT); while (true) { // 阻塞監聽 Socket socket = serverSocket.accept(); System.out.println("Client[" + socket.getPort() + "]Online"); // 讀取訊息 BufferedReader buffReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 傳送訊息 BufferedWriter buffWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); String msg = null; while ((msg = buffReader.readLine()) != null) { System.out.println("Client[" + socket.getPort() + "]:" + msg); // 寫入服務端要傳送的訊息 buffWriter.write("Server:" + msg + "\n"); buffWriter.flush(); if (msg.equals("quit")) { System.out.println("Client[" + socket.getPort() + "]:Offline"); break; } } } } catch (IOException e) { e.printStackTrace(); } } }