/** * @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) { } } }}
/** * @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()); } }}
1.发送消息的时候,一定要加上回车和换行符(rn),不然 scanner.nextLine() 无法识别到一行的结束,就会一直阻塞;