利用 Socket 模拟一个服务器来统一接收和发送消息
再用 Socket 模拟若干的客户端
服务端代码:
package com.wfChat.test;import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;public class SocketServer {public static void main(String[] args) {ServerSocket server = null;Map<String, Socket> CLENT_MAP = new HashMap<>();try {server = new ServerSocket(8848);System.out.println("服务已启动,等待客户端链接");while (true) {Socket socket = server.accept();String ip = socket.getInetAddress().getHostAddress();System.out.println("有客户端连接ip:" + ip + ",端口:" + socket.getPort());String clientKey = ip + socket.getPort();//将成功连接的客户端都加入 map 中CLENT_MAP.put(clientKey, socket);new Thread(() -> {while (true) {try {InputStream inputStream = socket.getInputStream();InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String readData = bufferedReader.readLine();System.out.println("收到客户端消息->" + readData);//给所有客户端发送消息CLENT_MAP.forEach((k, v) -> {try {OutputStream outputStream = v.getOutputStream();PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"));printWriter.println(socket.getPort() + ":" + readData);printWriter.flush();} catch (Exception e) {e.printStackTrace();}});} catch (Exception e) {e.printStackTrace();break;}}}).start();}} catch (Exception e) {e.printStackTrace();}}
}
客户端代码:
package com.wfChat.test;
import java.io.*;
import java.net.Socket;
import java.util.Scanner;public class SocketClient {public static void main(String[] args) {Socket socket = null;try {socket = new Socket("127.0.0.1", 8848);//输出流,输出内容到服务器OutputStream outputStream = socket.getOutputStream();PrintWriter printWriter = new PrintWriter(outputStream);System.out.println("请输入内容");new Thread(() -> {while (true) {Scanner scanner = new Scanner(System.in);String input = scanner.nextLine();try {printWriter.println(input);printWriter.flush();} catch (Exception e) {e.printStackTrace();break;}}}).start();//输入流,从服务器输入内容到客户端InputStream inputStream = socket.getInputStream();InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);new Thread(() -> {while (true) {try {String readData = bufferedReader.readLine();System.out.println("收到服务端消息" + readData);} catch (Exception e) {e.printStackTrace();break;}}}).start();} catch (Exception e) {e.printStackTrace();}}
}
测试:
我们将客户端的运行设置中的允许多次运行打开(在绿色小锤子的旁边可以看到这个界面):
然后,我们先将服务器启动,再用不同的客户端发送消息