前几个星期项目用到了webSocket,本来担心说没怎么用过,然而用起来轻松上手。(最近项目忙已经好久没写东西了,哈哈)
话不多说上代码。简单粗暴易懂。。。
以下为我使用的websocket配置。
/**
* 开启WebSocket支持
*/
@Configuration
public class WebSocketConfig {
//如果用外置tomcat,要注释掉以下代码,否则启动项目会报错,用springboot内置tomcat就得放开以下代码
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
下面是连接发送消息关闭连接配置的类
/**
* wensocket服务
*
*/
@ServerEndpoint("/websocket/{userId}")
@Component
@Slf4j
public class WebSocketServer {
/**
* 用来记录当前在线连接数
*/
private static int onlineCount = 0;
/**
* concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象
*/
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
/**
* 与某个客户端的连接会话,需要通过它来给客户端发送数据
*/
private Session session;
/**
* 接收userId
*/
private String userId;
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId) {
this.userId = userId;
this.session = session;
webSocketSet.add(this);
addOnlineCount();
log.info("连接建立:有一连接【{}】建立,当前在线人数为{}", userId, getOnlineCount());
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose(Session session, @PathParam("userId") String userId) {
webSocketSet.remove(this);
subOnlineCount();
log.info("连接关闭:有一连接【{}】关闭!当前在线人数为{}", userId, getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("客户端消息:收到来自窗口{}的信息:{}", userId, message);
try {
Instruction instruction = JSON.parseObject(message, Instruction.class);
int code = instruction.getCode();
if (code == INSTRUCTION_0.getCode()) {
//回执心跳
this.sendMessage(message);
} else {
String appID = instruction.getAppID();
//发送指令
for (WebSocketServer webSocketServer : webSocketSet) {
if (webSocketServer.userId.equals(appID)) {
webSocketServer.sendMessage(message);
}
}
}
} catch (Exception e) {
log.error("消息处理报错", e);
}
}
/**
* 发生错误
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误", error);
}
/**
* 单发消息
*
* @param message 消息
*/
public void sendMessage(String message) {
try {
this.session.getBasicRemote().sendText(message);
} catch (Exception e) {
log.error("发送消息错误", e);
}
}
/**
* 单发或群发消息
*
* @param message 消息
* @param userId 用户id
*/
public void sendInfo(String message, @PathParam("userId") String userId) {
log.info("发送自定义消息:推送消息到窗口{},推送内容:{}", userId, message);
for (WebSocketServer webSocketServer : webSocketSet) {
try {
//这里可以设定只推送给这个userId的,为null则全部推送
if (userId == null) {
webSocketServer.sendMessage(message);
} else if (webSocketServer.userId.equals(userId)) {
webSocketServer.sendMessage(message);
}
} catch (Exception e) {
log.error("单发或群发消息错误", e);
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
最后是配置的一个发送websocket消息的通用类
/**
* 指令
*
* @Description: 指令
* @Author: Rui3g
* @Date: 2019/12/26 10:30
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Instruction implements Serializable {
/**
* 标识
*/
private String appID;
/**
* 指令编码
*/
private Integer code;
/**
* 指令包含的传输数据
*/
private String data;
/**
* Message说明
*/
private String meaaage;
}
使用:new个WebSocketServer
先用实体类填入需要发送的信息,
我的做法是之后把实体转为json;
然后调用sendInfo发送消息,后面跟指定用户的唯一标识。
以上就是后端webSocket的使用。