WebSocketServer配置
@Slf4j
@ServerEndpoint(value = "/server/{userId}")
@Component
public class WebSocketServer {
private static int onlineCount = 0;
private static ConcurrentHashMap<String,WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
private Session session;
private String userId="";
@OnOpen
public void onOpen(Session session,@PathParam("userId") String userId) {
this.session = session;
this.userId=userId;
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
webSocketMap.put(userId,this);
}else{
webSocketMap.put(userId,this);
addOnlineCount();
}
log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
try {
sendMessage("用户".concat(userId)+"连接成功");
} catch (IOException e) {
log.error("用户:"+userId+",网络异常!!!!!!");
}
}
@OnClose
public void onClose() {
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
subOnlineCount();
}
log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
}
@OnMessage
public void onMessage(String message) {
log.info("用户消息:"+userId+",报文:"+message);
}
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
error.printStackTrace();
}
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
public static void sendInfo(String message,@PathParam("userId") String userId) throws IOException {
log.info("发送消息到:"+userId);
if(StringUtils.isNotBlank(userId)&&webSocketMap.containsKey(userId)){
webSocketMap.get(userId).sendMessage("测试消息推送到前端");
}else{
log.error("用户"+userId+",不在线!");
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
controller
@RestController
@RequestMapping("websocket")
public class WebSocketController {
@RequestMapping("/push/{toUserId}")
public ResponseEntity<String> pushToWeb( @PathVariable String toUserId) throws IOException {
String str ="消息测试推送至前端";
WebSocketServer.sendInfo(str,toUserId);
Map map = new HashMap();
map.put("message",str);
return ResponseEntity.ok(JSON.toJSONString(map));
}
}
pom依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.44</version>
</dependency>
</dependencies>
启动项
@Slf4j
@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
public class WebsocketApplication {
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
ApplicationContext context = SpringApplication.run(WebsocketApplication.class, args);
long endTime = System.currentTimeMillis();
log.info("\n _ooOoo_ \n" +
" o8888888o \n" +
" 88\" . \"88 \n" +
" (| -_- |) \n" +
" O\\ = /O \n" +
" ____/`---'\\____ \n" +
" . ' \\\\| |// `. \n" +
" / \\\\||| : |||// \\ \n" +
" / _||||| -:- |||||- \\ \n" +
" | | \\\\\\ - /// | | \n" +
" | \\_| ''\\---/'' | | \n" +
" \\ .-\\__ `-` ___/-. / \n" +
" ___`. .' /--.--\\ `. . __ \n" +
" .\"\" '< `.___\\_<|>_/___.' >'\"\". \n" +
" | | : `- \\`.;`\\ _ /`;.`/ - ` : | | \n" +
" \\ \\ `-. \\_ __\\ /__ _/ .-` / / \n" +
" ======`-.____`-.___\\_____/___.-`____.-'====== \n" +
" `=---=' \n" +
" \n" +
" ............................................. \n" +
" 启动成功 佛祖保佑 代码永无BUG 需求永不变更");
log.info(
"Application {} 启动成功, 应用端口 {}, 耗时 {} 秒, 加载 Spring 组件 {} 个.\nApplication Path: {}.\nApplication Version: {}.",
WebsocketApplication.class.getName(),
context.getEnvironment().getProperty("server.port"),
(endTime - startTime) / 1000.00,
context.getBeanDefinitionNames().length,
Thread.currentThread().getContextClassLoader().getResource("").getPath(),
"1.0.0-build");
}
}