webSocket可实现网页端与服务端之间的双向信息传送,是一种全双工的通信方式,下面我们来看连接配置代码实现:
①添加好pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
②编写WebSocketConfig配置类
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
private Logger log = LogManager.getLogger(WebSocketConfig.class);
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry){
/**这个地址要和前端js配置中的地址统一*/
String mapping = "/collection/test";
registry.addHandler(webSocketHandler(),mapping).addInterceptors();
log.info("WebSocket已注册成功,WB地址:" + mapping);
}
@Bean
public WebSocketHandler webSocketHandler(){
return new WbHandler();
}
}
③编写WebSocketHandler类
public class WbHandler implements WebSocketHandler {
private static final Logger log = LogManager.getLogger(WbHandler.class);
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus arg1) throws Exception{
log.info("正常日志:"+session.getRemoteAddress()+"断开连接!");
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception{
log.info("正常日志:"+session.getRemoteAddress()+"打开连接!");
}
@Override
public void handleMessage(WebSocketSession conn, WebSocketMessage<?> message) throws Exception {
log.info("日志信息:"+message.getPayload());
conn.sendMessage(new TextMessage("ok"));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable arg1) throws Exception {
if(session.isOpen()){
session.close();
}
log.error( "出错日志: IP:" +session.getRemoteAddress()+" "+ arg1.getMessage() );
}
@Override
public boolean supportsPartialMessages() {
return false;
}
④前端js代码配置
var ws;
function connectWS(command) {
/**当前路径地址*/
var path = window.location.pathname;
/**当前主机地址*/
var hostaddress = window.location.host + path.substring(0,path.substr(1).indexOf('/')+1);
console.log(hostaddress);
/**后台wb控制器url*/
var target = "/test";
/**将http协议换成ws*/
if (window.location.protocol == 'http:') {
target = 'ws://' + hostaddress + target;
} else {
target = 'wss://' + hostaddress + target;
}
console.log('WebSocketServer地址:'+target);
/**创建一个针对控制器的 webSocket 对象*/
if ('WebSocket' in window) {
ws = new WebSocket(target);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(target);
} else {
$.modal.confirm("您的浏览器不支持 WebSocket!");
return;
}
console.log("ws:",ws);
/**如果没有ws对象 直播状态为2 设置对应按钮*/
if(ws==null){
console.log("WebSocket创建失败...")
}
/**开启WS*/
ws.onopen = function () {
/**向后台发送指令*/
startsent(command);
console.log('发送控制命令');
};
/**WS的返回信息*/
ws.onmessage = function (event) {
console.log('WS接收到的信息:' + event.data);
};
/**WS关闭*/
ws.onclose = function (event) {
console.log('WS已关闭:' + event.data );
};
}
function startsent(command){
if (ws != null) {
console.log('开始发送Wb指令');
/**向后台发送信息*/
ws.send(command);
} else {
$.modal.confirm("WebSocket 连接建立失败,请重新连接");
}
}
⑤前端html调用js
<div class="ibox">
<div class="ibox-content">
<button type="button" class="btn btn-primary" onclick="connectWS(this.value)" value="01"> 开启采集</button>
<button type="button" class="btn btn-primary" onclick="connectWS(this.value)" value="02"> 关闭采集</button>
</div>
</div>
效果展示
后台日志前端日志