简介
websocket用于web页面中实时刷新数据,服务端可主动向页面推送消息。(搜这个的都知道,但是大家又都写,我也不知道为啥就跟着介绍了以下),这里介绍的是springboot中的使用后台代码
看到这个的肯定都会搭建boot,这里附上依赖,和代码
先截图解释
pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
主要代码类
@Component
@ServerEndpoint("/webSocket/{username}")//encoders = { ServerEncoder.class },可选值,指定编码转换器,传输对象时用到,这里直接转json就ok
public class WebSocketService {
private static final Map<String,Session> TOKEN_SESSION = new HashMap<>();
private static final Map<String,String> SESSION_ID_TOKEN = new HashMap<>();
private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss");
@PostConstruct
public void refreshDate(){
Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(()->{
sendMessage(FORMAT.format(new Date()));
},1000,1000,TimeUnit.MILLISECONDS);
}
@OnOpen
public void onOpen(Session session,@PathParam("username")String username){
System.out.println("新的连接进来了"+session.getId());
if (username == null){
try {
session.close(new CloseReason(CloseReason.CloseCodes.CANNOT_ACCEPT,"username参数为空"));
} catch (IOException e) {
throw new IllegalStateException(e.getMessage());
}
}else {
SESSION_ID_TOKEN.put(session.getId(),username);
TOKEN_SESSION.put(username,session);
System.out.println(username);
}
}
@OnClose
public void onColse(Session session){
System.out.println("断开连接"+session.getId());
}
@OnMessage
public void onMessage(Session session,String message){
System.out.println("收到客户端发来的消息:"+message+session.getId());
sendMessageToTarget(SESSION_ID_TOKEN.get(session.getId()),message+"已收到");
}
public void sendMessage(String message){
System.out.println("发送全体消息");
TOKEN_SESSION.values().forEach((session)->{
session.getAsyncRemote().sendText(message);
});
}
public <T> void sendMessageToTarget(String token,Object t){
System.out.println("发送指定token消息");
try {
TOKEN_SESSION.get(token).getBasicRemote().sendText((String)t);
} catch (Exception e) {
e.printStackTrace();
}
}
}
根据打包类型可选配置类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointConfigurator(){
return new ServerEndpointExporter();
}
}
截图是主要解释,代码为了方便学习的小伙伴cv
前台主要代码(这里用的vue写的前台)
截图解释
附上代码(作为一名后端,我是不太暴露我的前台代码的。。。):
<template>
<div class="layout">
<div class="msgBody">{{msg}}</div>
<input v-model="sendMsg" />
<button @click="sendMessage">发送</button>
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'LayOut',
data(){
return{
msg:'',
sendMsg:'',
path:"ws://127.0.0.1:18989/webSocket/admin",
socket:"",
}
},
methods:{
sendMessage(){
this.socket.send(this.sendMsg)
},
init(){
if(typeof(WebSocket) === "undefined"){
alert("您的浏览器不支持socket")
}else{
// 实例化socket
this.socket = new WebSocket(this.path)
// 监听socket连接
this.socket.onopen = this.open
// 监听socket错误信息
this.socket.onerror = this.error
// 监听socket消息
this.socket.onmessage = this.getMessage
this.socket.onclose = this.close
}
},
open: function () {
console.log("socket连接成功")
},
error: function (err) {
console.log("连接错误"+err)
},
getMessage: function (msg) {
this.msg = msg.data;
},
close: function (event) {
console.log("socket已经关闭"+event.reason)
},
},
created(){
this.init();
}
}
</script>
<style scoped>
.layout{
position: relative;
width: 100%;
height: 100%;
}
.msgBody{
width: 300px;
height: 300px;
border: 1px solid rgb(95, 79, 79);
}
</style>
效果
以上就是全部截图介绍,以及代码。这里说一下我的应用场景,作为写上位机,需要实时检测显示下位机的状态,如果用简单的断轮询,或长轮询都没那么好的及时性以及性能,所以websocket是最好的选择。又不懂的地方可以留言联系