【1】socket服務器
/** * @Description 即時消息服務器 * @author xiao tang * @version 1.0.0 * @createTime 2022年01月23日 */public class IMSocketServer { private static int PORT = 13; public static void main(String[] args) { ServerSocket server = null; try { // 開啟端口 server = new ServerSocket(PORT); System.out.println("服務器已啟動"); // 與客戶端建立socket連接 Socket socket = server.accept(); System.out.println("客戶端請求,創建連接成功"); // 寫出器 PrintWriter writer2Client = new PrintWriter(socket.getOutputStream()); writer2Client.write("連接創建成功rn"); writer2Client.flush(); // 客戶端讀入器 Scanner scanner4Client = new Scanner(socket.getInputStream()); // 控制臺讀入器 Scanner scanner4Console = new Scanner(System.in); // 等待客戶端輸入 while(true) { // 讀取客戶端消息并打印 String msg4Client = scanner4Client.nextLine(); System.out.println("客戶端:" + msg4Client); System.out.print("服務端:"); // 獲取控制臺輸入數據并發送到客戶端 String msg4Console = scanner4Console.nextLine(); writer2Client.write(msg4Console + "rn"); writer2Client.flush(); } } catch (IOException e) { throw new MyRunTimeException("打開端口socket失敗,端口=" + PORT + ", 異常信息=" + e.getMessage()); } finally { try { if (server != null) { server.close(); } } catch (Exception e) { } } }}
【2】socket客戶端
/** * @Description 即時消息客戶端 * @author xiao tang * @version 1.0.0 * @createTime 2022年01月23日 */public class IMSocketClient { private static int PORT = 13; public static void main(String[] args) { try (Socket socket = new Socket()) { // 與服務器端建立socket連接 socket.connect(new .NETSocketAddress("localhost", PORT), 3000); // 新建讀取器,寫出器 Scanner scanner4Server = new Scanner(socket.getInputStream()); PrintWriter printWriter = new PrintWriter(socket.getOutputStream()); // 控制臺讀入器 Scanner scanner4Console = new Scanner(System.in); System.out.println("連接成功,等待服務器響應"); // 等待服務器控制臺輸入 while(true) { // 讀取服務器響應并打印 String msg4Server = scanner4Server.next(); System.out.println("服務器:" + msg4Server); System.out.printf("n客戶端:"); // 客戶端讀取控制臺輸入,并發送到服務器 String msg4Console = scanner4Console.nextLine(); printWriter.write(msg4Console + "rn"); printWriter.flush(); } } catch (Exception e) { throw new MyRunTimeException("客戶端通訊失敗, 異常信息=" + e.getMessage()); } }}
【3】通訊效果

【4】注意事項
1.發送消息的時候,一定要加上回車和換行符(rn),不然 scanner.nextLine() 無法識別到一行的結束,就會一直阻塞;