1.Websocket初识
HTTP 协议有一个缺陷:通信只能由客户端发起,HTTP 协议做不到服务器主动向客户端推送信息。
而Websocket,浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。
当你获取 Web Socket 连接后,你可以通过 send来向服务器发送数据,并通过 onmessage 事件来接收服务器返回的数据。
2.Websocket实现
2.1 gradle依赖添加
//websocket
implementation('org.springframework.boot:spring-boot-starter-websocket')
2.2 Websocket配置
@Configuration
public class WebSocketConfig {
/**
* 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
2.3 WebSocketServer配置
@ServerEndpoint(value = "/websocket/{sid}")
@Component
public class WebSocketServer {
static Log log= LogFactory.get(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
//接收sid
private String sid="";
/**
* 连接建立成功调用的方法
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + getOnlineCount());
this.sid=sid;
try {
sendString("successfulconnection");
log.info("【websocket消息】有新的连接, 总数:{}", webSocketSet.size());
} catch (IOException e) {
log.error("websocket IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
log.info("有一连接关闭!当前在线人数为" + getOnlineCount());
log.info("【websocket消息】连接断开, 总数:{}", webSocketSet.size());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("收到来自窗口"+sid+"的信息:"+message);
//群发消息
for (WebSocketServer item : webSocketSet) {
try {
item.sendString(message);
log.info("【websocket消息】收到客户端发来的消息:{}", message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
/**
* 实现服务器主动推送
*/
public void sendString(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 群发自定义消息,发送对象
* */
public static void sendObjectInfo(Object object,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+object);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.session.getBasicRemote().sendObject(object);
} else if (item.sid.equals(sid)){
item.session.getBasicRemote().sendObject(object);
}
} catch (IOException e) {
try {
webSocketSet.remove(item);
item.session.close();
} catch (Exception ex) {
ex.printStackTrace();
}
continue;
} catch (EncodeException e) {
e.printStackTrace();
}
}
log.info("【websocket消息】广播消息, message={}", object);
}
/**
* 群发自定义消息,发送字符串
* */
public static void sendStringInfo(String message,@PathParam("sid") String sid) throws IOException {
log.info("推送消息到窗口"+sid+",推送内容:"+message);
for (WebSocketServer item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sid==null) {
item.sendString(message);
}else if(item.sid.equals(sid)){
item.sendString(message);
}else{
item.sendString("hey hey hey");
}
} catch (IOException e) {
continue;
}
}
log.info("【websocket消息】广播消息, message={}", message);
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
2.4 WebSocket消息推送
WebSocketServer.sendStringInfo(message, sid);
2.5 web页面发起socket请求
//index.js
export default {
// websocket
websocket: '',
// 创建websocket链接
connectWebsocket (val) {
let _this = this
let user = 0
const baseUrl = "http://192.168.1.60:8081"
if (typeof (WebSocket) === 'undefined') {
alert('您的浏览器不支持socket')
} else {
// 实例化websocket
var path = baseUrl.replace('http', 'ws') + '/websocket/' + val
_this.websocket = ''
_this.websocket = new WebSocket(path)
// 监听websocket连接
_this.websocket.onopen = function (event) {
console.log('建立连接')
sessionStorage.setItem('ws', _this.websocket)
}
// 监听websocket错误信息
_this.websocket.onerror = function () {
alert('websocket通信发生错误!')
}
// websocket
_this.websocket.onmessage = function (event) {
var t
if (event.data) {
try {
// 封装返回的数据
if (t instanceof Object) {
t = JSON.parse(event.data)
} else {
t = event.data
}
console.log(t)
} catch (e) {
// 如果是字符串则直接赋值
t = event.data
}
}
}
// websocket
_this.websocket.onclose = function (event) {
console.log('连接关闭')
_this.websocket = ''
sessionStorage.removeItem('ws')
}
// 页面刷新时关闭连接(此处不写一样会关闭,因一些原因要写上)
window.onbeforeunload = function () {
_this.websocket.close()
_this.websocket = ''
sessionStorage.removeItem('ws')
}
}
}
}
//main.js调用
import Utils from './util'
Utils.connectWebsocket(sid)
2.6 Vue组件引用
<template>
<div>
<h1>{{socketMsg}}</h1>
</div>
</template>
<script>
export default {
name: "SocketDemo",
data() {
return {
socket: null,
socketMsg: null,
}
},
mounted() {
var that = this
console.log("demo socket 初始化!!!")
// 代码片段
/**
* 页面发起socket 请求
* @type {WebSocket}
*/
that.socket = new WebSocket("ws://localhost:8081/websocket/2");
that.socket.onopen = function () {
console.log("Socket 已打开");
};
that.socket.onmessage = function (msg) {
that.socketMsg = msg.data
console.log('收到消息 this.socketMsg===' + that.socketMsg)
};
that.socket.onclose = function () {
console.log("this.socket已关闭");
};
that.socket.onerror = function () {
console.log("Socket发生了错误");
}
},
methods: {}
}
</script>
参考来源:https://blog.csdn.net/a12hhhe/article/details/100538086