websocket
作者:互联网
maven
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</dependency>
WebSocketConfig
package com.new3s.common.framework.socket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @Description webSocket 配置类
* @Date 2022-08-27
* @Author xie
*/
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServer
package com.new3s.pvinspection.socket;
import com.new3s.common.core.exception.ServiceException;
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.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Description WebSocket 服务
* @Date 2022-08-27
* @Author xie
*/
@ServerEndpoint("/websocket/pv/airline/{uid}")
@Component
public class AirlineWebSocketServer {
private static Logger log = LoggerFactory.getLogger(AirlineWebSocketServer.class);
private static final AtomicInteger onlineNum = new AtomicInteger(0);
private static CopyOnWriteArraySet<Session> sessionPools = new CopyOnWriteArraySet<>();
@OnOpen
public void onOpen(Session session, @PathParam(value = "uid") String uid) {
sessionPools.add(session);
onlineNum.incrementAndGet();
log.info("{}: 加入到websocket. 当前连接数:{}", uid, onlineNum);
try {
sendMessage(session, "WebSocket连接成功");
} catch (IOException e) {
log.error("WebSocket IO异常");
}
}
@OnClose
public void onClose(Session session) {
sessionPools.remove(session);
onlineNum.decrementAndGet();
log.info("有连接关闭, 当前连接数:{}", onlineNum);
}
@OnError
public void one rror(Session session, Throwable exception) {
log.error("连接错误:{}", exception);
throw new ServiceException(exception.getMessage());
}
@OnMessage
public void onMessage(Session session, String message) {
log.info("来自客户端的消息:" + message);
try {
//sendMessage(session, message);
broadCastInfo(message);
} catch (IOException e) {
e.printStackTrace();
log.error("发送WebSocket IO异常: {}", e);
}
}
public void sendMessage(Session session, String message) throws IOException {
if (null != session) {
synchronized (session) {
session.getBasicRemote().sendText(message);
}
}
}
public void broadCastInfo(String message) throws IOException {
for (Session session : sessionPools) {
if (session.isOpen()) {
sendMessage(session, message);
}
}
}
}
websocket测试
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>实时监控</title>
</head>
<style>
.item {
display: flex;
border-bottom: 1px solid #000000;
justify-content: space-between;
width: 30%;
line-height: 50px;
height: 50px;
}
.item span:nth-child(2){
margin-right: 10px;
margin-top: 15px;
width: 20px;
height: 20px;
border-radius: 50%;
background: #55ff00;
}
.nowI{
background: #ff0000 !important;
}
</style>
<body>
<div id="app">
<div v-for="item in list" class="item">
<span>{{item.id}}.{{item.name}}</span>
<span :class='item.state==-1?"nowI":""'></span>
</div>
</div>
</body>
<script src="./js/vue.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
list: [{
id: 1,
name: '张三',
state: 1
},
{
id: 2,
name: '李四',
state: 1
},
{
id: 3,
name: '王五',
state: 1
},
{
id: 4,
name: '韩梅梅',
state: 1
},
{
id: 5,
name: '李磊',
state: 1
},
]
}
})
var webSocket = null;
if ('WebSocket' in window) {
//创建WebSocket对象
webSocket = new WebSocket("ws://localhost:8080/websocket/pv/airline/" + getUUID());
//连接成功
webSocket.onopen = function() {
console.log("已连接");
webSocket.send("消息发送测试")
}
//接收到消息
webSocket.onmessage = function(msg) {
//处理消息
var serverMsg = msg.data;
var t_id = parseInt(serverMsg) //服务端发过来的消息,ID,string需转化为int类型才能比较
for (var i = 0; i < vm.list.length; i++) {
var item = vm.list[i];
if(item.id == t_id){
item.state = -1;
vm.list.splice(i,1,item)
break;
}
}
};
//关闭事件
webSocket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
webSocket.onerror = function() {
console.log("websocket发生了错误");
}
} else {
alert("很遗憾,您的浏览器不支持WebSocket!")
}
function getUUID() { //获取唯一的UUID
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
</script>
</html>
标签:websocket,log,public,session,import,id 来源: https://www.cnblogs.com/mask-xiexie/p/16638782.html