一、后端代码
1. 配置WebSocket连接信息
一个是WebSocket配置bean,另一个是WebSocketServer
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();
}
}
import com.alibaba.fastjson.JSONObject;
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;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Component
@ServerEndpoint("/websocket/{socketname}")
public class WebSocketServer {
private Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 以通道名称为key,连接会话为对象保存起来
*/
public static Map<String, WebSocketServer> websocketClients = new ConcurrentHashMap<String, WebSocketServer>();
/**
* 会话
*/
private Session session;
/**
* 通道名称
*/
private String socketname;
/**
* 发送消息到指定连接
* @param socketname 连接名
* @param jsonString 消息
*/
public void sendMessage(String socketname, String jsonString){
WebSocketServer nowsession = websocketClients.get(socketname);
if(nowsession!=null){
try {
nowsession.session.getBasicRemote().sendText(jsonString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@OnOpen
public void onOpen(@PathParam("socketname") String socketname, Session session)
{
this.socketname = socketname;
this.session = session;
if(websocketClients.get(socketname)==null){
websocketClients.put(socketname, this);
System.out.println("当前socket通道"+socketname+"已加入连接");
}
}
@OnError
public void onError(Session session, Throwable error) {
logger.info("服务端发生了错误"+error.getMessage());
}
/**
* 连接关闭
*/
@OnClose
public void onClose()
{
websocketClients.remove(socketname);
System.out.println("当前socket通道"+socketname+"已退出连接");
}
/**
* 收到客户端的消息
*
* @param message 消息
* @param session 会话
*/
@OnMessage
public void onMessage(String message, Session session){
System.out.println("当前收到了消息:"+message);
session.getAsyncRemote().sendText("来自服务器:"+this.socketname+"你的消息我收到啦");
};
/**
* 向所有连接主动推送消息
* @param jsonObject 消息体
* @throws IOException
*/
public void sendMessageAll(JSONObject jsonObject) throws IOException {
for (WebSocketServer item : websocketClients.values()) {
item.session.getAsyncRemote().sendText(jsonObject.toJSONString());
}
}
}
1.2 前端代码
// Socket 连接
initWebSocket: function () {
// WebSocket与普通的请求所用协议有所不同,ws等同于http,wss等同于https
this.websock = new WebSocket('ws://127.0.0.1:8080/websocket/nice')
this.websock.onopen = this.webSocketOnOpen
this.websock.onerror = this.websSocketOnError
this.websock.onmessage = this.webSocketOnMessage
},
webSocketOnOpen: function () {
console.log('WebSocket连接成功')
},
websSocketOnError: function (e) {
console.log('WebSocket连接发生错误')
this.reconnect()
},
webSocketOnMessage: function (e) {
// 这里是接收消息,收到消息后的处理逻辑
},
webSocketClose: function (e) {
console.log('connection closed (" + e.code + ")')
},
webSocket0Close: function () {
let url = 'ws://127.0.0.1:8080/websocket/nice'
// 这里只是一个基于axios的ajax请求,你可以换成你的请求格式
this.$ajax.get(url)
},
// 重连
reconnect: function () {
setTimeout(
// 没连接上会一直重连,设置延迟避免请求过多
this.initWebSocket(), 2000)
}
destroyed: function () {
// 离开页面生命周期函数
this.webSocket0Close()
},