1、pom.xml引入jar
org.springframework.boot spring-boot-starter-websocket
2、创建WebSocket配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3、创建WebSocket服务
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint("/socketServer/{uid}")
@Slf4j
public class WebSocketServer {
private static UserService userService;
// @Autowired只能在set方法注入,不然会null报错
@Autowired
public void setUserService(UserService userService) {
WebSocketServer.userService = userService;
}
private static int onlineCount = 0;
private Session session;
private String uid = "";
private static ConcurrentHashMap webSocketMap = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session, @PathParam("uid") String uid) {
log.info("用户连接建立成功:"+uid);
this.session = session;
this.uid = uid;
if (webSocketMap.containsKey(uid)) {
webSocketMap.remove(uid);
//加入到set中
webSocketMap.put(uid, this);
} else {
//加入set中
webSocketMap.put(uid, this);
//加入set中
addOnlineCount();
//在线数加1
}
try {
sendMsg("{"status": "加入成功"}");
} catch (IOException e) {
log.error("用户:" + uid + ",网络异常!!!!!!");
}
}
@OnClose
public void onClose() {
if (webSocketMap.containsKey(uid)) {
webSocketMap.remove(uid);
//从set中删除
subOnlineCount();
}
}
@OnMessage
public void onMessage(String message) {
log.info("收到用户消息:"+uid+",报文:"+message);
try {
// 给uid发送消息
webSocketMap.get(uid).sendMsg(message);
} catch (IOException e) {
e.printStackTrace();
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:" + this.uid + ",原因:" + error.getMessage());
error.printStackTrace();
}
private void sendMsg(String msg) throws IOException {
this.session.getBasicRemote().sendText(msg);
}
private static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
private static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
4、可以自己创建一个测试页面链接websocket地址:
ws://localhost:8080/socketServer/40
websocket测试
点击测试连接 WebSocket



