写这篇博客记录一下自己在用websocket的时候遇到的坑。
需求是这样的:需要将activeMq来的数据利用websockt推送给客户端显示出来,有多个服务终端,需要将不同的消息推送到对应的服务终端上。
1.服务端代码:需要写一个WebSocketServer类,里面根据自己需要重写方法,在写一个配置类WebSocketConfig就行了。下面上代码
WebSocketServer类:
@Component
//访问服务端的url地址
@ServerEndpoint(value = "/websocket/{id}")
public class WebSocketServer {
private static int onlineCount = 0;
private static ConcurrentHashMap<String, WebSocketServer> webSocketSet = new ConcurrentHashMap<>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private static Logger log = LogManager.getLogger(WebSocketServer.class);
private String id = "";
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(@PathParam(value = "id") String id, Session session) {
this.session = session;
this.id = id;//接收到发送消息的人员编号
webSocketSet.put(id, this); //加入set中
addOnlineCount(); //在线数加1
log.info("用户"+id+"加入!当前在线人数为" + getOnlineCount());
System.out.println("连接成功");
try {
sendMessage("连接成功");
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("来自客户端的消息:" + message);
//可以自己约定字符串内容,比如 内容|0 表示信息群发,内容|X 表示信息发给id为X的用户
String sendMessage = message.split("[|]")[0];
String sendUserId = message.split("[|]")[1];
try {
if(sendUserId.equals("0")) {
sendtoAll(sendMessage);
}else {
sendtoUser(sendMessage, sendUserId);
}