1.实现实时聊天
1.服务端建立一个ConcurrentHashMap<> 用来存储在线用户,用户账号和socket然后,如果有个人发了信息,就去数据库中查询,然后根据这个在线用户进行传递信息
服务端框架:
public class ServerMain {private static ConcurrentHashMap<Integer, Socket> onlineUsers = new ConcurrentHashMap<>();public static void main(String[] args) throws Exception {ServerSocket serverSocket = new ServerSocket(8888);//返回一个最多5个线程的线程池ExecutorService es = Executors.newFixedThreadPool(5);while (true) {Socket socket = serverSocket.accept();es.submit(new myRunnable(socket,onlineUsers));}}
}
public class myRunnable implements Runnable {private Socket socket;private VerificationCodeTool verificationCodeTool = new VerificationCodeTool();//记录在线用户,不断更新界面private ConcurrentHashMap<Integer, Socket> onlineUsers;Student student;Teacher teacher;int UserId; //用来删除public myRunnable(Socket socket,ConcurrentHashMap onlineUsers) {this.socket = socket;this.onlineUsers = onlineUsers;}@Overridepublic void run() {long lastTime = 0;while (!socket.isClosed()) {try {Message requestMessage = SocketUtil.getSocketUtil().getMessage(socket);if (requestMessage == null) {System.out.println("message 为空");break;}//后面进行请求操作
2. 客户端搞长连接,还有主控制类,在主控制类中调用方法,实时更新ui,
客户端根据请求进行处理:
专门搞个线程,进行长连接,处理服务端发过来的请求。
服务端处理请求线程: