文件名称 | 版本号 | 作者 | 版本 | |
---|---|---|---|---|
WS | v1.0.0 | 学生宫布 | 8416837 | SpringBoot 2.2.6 SpringCloud Hoxton.SR4 |
IM
服务端转发模式
机器人检索
群-广播
通信流程
代码-js版
C/S B/S Java作服务端
套路
废话不多说,直接套路
代码
引入依赖
- websocket
<!-- websocket-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<!-- 使用RELEASE作为版本号会不断升级-->
<version>2.1.6.RELEASE</version>
</dependency>
启用Websocket的配置
- 不含包名
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* 功能:创建Bean
*
* @author: cc
* @qq: 8416837
* @date: 2020/9/23 9:42
*/
@Configuration
public class WebsocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
前后端连接成功后执行的代码
如果前端报错:WebSocket handshake: Unexpected response code: 200,
则可能是security或shiro权限拦截了,解决办法:附权限或者放行
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
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;
/**
* 功能:服务器
*
* @author: cc
* @qq: 8416837
* @date: 2020/9/23 9:44
*/
@Api(tags = "Xxx管理推送")
@ServerEndpoint("/Xxx/{projectId}")
@Component
@Slf4j
public class WebSocketServer {
/**
* 静态变量,用来记录当前在线连接数。todo 应该把它设计成线程安全的。
*/
private static int onlineCount = 0;
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
*/
private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 接收userId
*/
private String projectId = "";
/**
* 连接建立成功调用的方法
*/
@ApiOperation(value = "获取ws之前端请求", notes = "projectId:项目名称;type:1=实验集任务;2=模型任务;", tags = "")
@OnOpen
public void onOpen(Session session, @PathParam("projectId") String projectId, @PathParam("type") String type) {
this.session = session;
this.projectId = projectId;
if (webSocketMap.containsKey(projectId)) {
webSocketMap.remove(projectId); // 业务幂等用户
//加入set中
} else {
//加入set中
addOnlineCount();
//在线数加1
}
webSocketMap.put(projectId, this);
log.debug("用户连接:{},当前在线人数为:{}", projectId, getOnlineCount());
try {
sendMessage("连接成功"); // 连接成功就是发送给前端的消息
} catch (IOException e) {
log.error("用户:{},网络异常 => {}", projectId, e.toString());
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
if (webSocketMap.containsKey(projectId)) {
webSocketMap.remove(projectId);
//从set中删除
subOnlineCount();
}
log.debug("用户退出:{},当前在线人数为:{}", projectId, getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) { // 场景是聊天
log.debug("用户消息:{},报文:{}", projectId, message);
//可以群发消息
//消息保存到数据库、redis
if (StringUtils.isNotBlank(message)) {
try {
//解析发送的报文
JSONObject jsonObject = JSON.parseObject(message);
//追加发送人(防止串改)
jsonObject.put("fromUserId", this.projectId);
String toUserId = jsonObject.getString("toUserId");
//传送给对应toUserId用户的websocket
if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
} else {
log.error("请求的projectId:{},不在该服务器上", toUserId);
//否则不在这个服务器上,发送到mysql或者redis
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("{}错误:{}", this.projectId, error.getMessage());
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 发送自定义消息 在controller调用这个接口,发送消息
*/
public static void sendInfo(String message, @PathParam("projectId") String projectId) throws IOException {
log.debug("发送消息到 => {},报文:{}", projectId, message);
if (StringUtils.isNotBlank(projectId) && webSocketMap.containsKey(projectId)) {
webSocketMap.get(projectId).sendMessage(message);
} else {
log.debug("用户:{}不在线", projectId);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
刷新前端,跑起来
- 后端准备发送数据:
- 前端收到信息:
console.log(`后端发送的消息:`, msg.data)
说明交互成功
关闭Socket
1)刷新页面
2)Server故障;
坑
- 前端也可以向后端发送消息
- 心跳模式,需要自己写定时器实现,它好像并不会有心跳API;
介绍
优点
前后端对等
websocket其他特点如下:
(1)建立在 TCP 协议之上,服务器端的实现比较容易。
(2)与 HTTP 协议有着良好的兼容性。默认端口也是80和443,并且握手阶段采用 HTTP 协议,因此握手时不容易屏蔽,能通过各种 HTTP 代理服务器。
(3)数据格式比较轻量,性能开销小,通信高效。
(4)可以发送文本,也可以发送二进制数据。
(5)没有同源限制,客户端可以与任意服务器通信。
(6)协议标识符是ws(如果加密,则为wss),服务器网址就是 URL。