pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
config:
package com.zjzy.config;
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();
}
}
服务端:
package com.zjzy.controller;
import com.alibaba.fastjson.JSONObject;
import com.zjzy.utils.WebSocketMapUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
/**
* 多例,每个MyWebSocketServer对象对应一个用户连接。
* 把用户标识(如用户名,这里为session_id)和其MyWebSocketServer对象作为key-value键值对,存在全局map中。这样一个用户能发送消息到另一个用户
*/
@ServerEndpoint(value = "/websocket/{sid}")
@Component
public class MyWebSocketServer {
private static Logger logger = LoggerFactory.getLogger(MyWebSocketServer.class);
private Session session;
/**
* * 连接建立后触发的方法
*
*/
@OnOpen
public void onOpen(@PathParam(value = "sid") String sid,Session session) {
System.out.println("sid:"+sid);
this.session = session;
// System.out.println(this);//验证此类是多例
logger.info("onOpen" + session.getId());
WebSocketMapUtil.put(session.getId(), this);
}
/**
* * 连接关闭后触发的方法
*
*/
@OnClose
public void onClose() {
//从map中删除
WebSocketMapUtil.remove(session.getId());
logger.info("====== onClose:" + session.getId() + " ======");
}
/**
* * 接收到客户端消息时触发的方法
*
*/
@OnMessage
public void onMessage(String params, Session session) throws Exception {
//获取服务端到客户端的通道
MyWebSocketServer myWebSocket = WebSocketMapUtil.get(session.getId());
logger.info("收到来自" + session.getId() + "的消息" + params);
String result = "收到来自" + session.getId() + "的消息" + params;
//返回消息给Web Socket客户端(浏览器)
// myWebSocket.sendMessage(1, "成功!", result);
myWebSocket.sendAll(result);
}
/**
* 发生错误时触发的方法
*
*/
@OnError
public void onError(Session session, Throwable error) {
logger.info(session.getId() + "连接发生错误" + error.getMessage());
error.printStackTrace();
}
/**
* 发送一条json数据
* @param datas
* @throws IOException
*/
public void sendMessage(Object datas) throws IOException {
JSONObject result = new JSONObject();
result.put("datas",datas);
this.session.getBasicRemote().sendText(result.toString());
}
/**
* 给指定用户发消息
* @param id 用户标识
* @param datas 数据
* @throws IOException
*/
public void sendMessage(String id, Object datas) throws IOException {
JSONObject result = new JSONObject();
result.put("datas",datas);
MyWebSocketServer myWebSocketServer = WebSocketMapUtil.get(id);
myWebSocketServer.session.getBasicRemote().sendText(result.toString());
}
// public void sendMessage(int status, String message, Object datas) throws IOException {
// JSONObject result = new JSONObject();
// result.put("status", status);
// result.put("message", message);
// result.put("datas", datas);
// this.session.getBasicRemote().sendText(result.toString());
// }
/**
* 给所有用户发消息
* @param datas 数据
* @throws IOException
*/
public void sendAll(Object datas) throws IOException {
for(MyWebSocketServer myWebSocketServer:WebSocketMapUtil.getValues()){
myWebSocketServer.sendMessage(datas);
}
}
}