目录
前言
想实现websocket通信并不复杂,这篇文章列举了多种选择,感兴趣的可以移步了解。
一文搞懂四种 WebSocket 使用方式,建议收藏! – 知乎 (zhihu.com)
而本文是使用ServerEndpoint实现的。
SpringBoot
使用maven添加依赖
maven搭建springboot环境可以参考博主的这篇文章。
【web系列十六】idea下使用Maven搭建spring boot开发环境_Nicholson07的博客-CSDN博客
找到pom.xml添加以下内容
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
创建websocket服务
创建service文件夹及WebSocket.java
@Component
@Slf4j
@ServerEndpoint(value = "/websocket/{sessionId}")
public class WebSocket {
public static int onlineCount = 0;
public static Map<String, WebSocket> clients = new HashMap<String, WebSocket>();
public Session session;
public String sessionId;
public String getsessionId() {
return sessionId;
}
public static void sendMessageTo(JSONObject json) {
log.warn("sendMsg:"+json);
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(json.toJSONString());
}
}
@OnOpen
public void onOpen(@PathParam("sessionId") String sessionId, Session session) throws IOException {
this.sessionId = sessionId;
this.session = session;
clients.put(session.getId(), this);
log.warn("已连接:"+sessionId);
JSONObject msg = new JSONObject();
msg.put("msg", "spring send msg");
this.sendMessageTo(msg);
}
@OnClose
public void onClose() throws IOException {
log.warn("断开"+sessionId);
clients.remove(session.getId());
}
//收到客户端消息后调用的方法
@OnMessage
public void onMessage(String message) throws IOException {
if(message.equals("ping")) {
this.session.getAsyncRemote().sendText("pang");
}else if("close".equals(message)) {
onClose();
this.session.close();
}else {
log.warn(this.sessionId+"收到 "+message);
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
public static synchronized int getOnlineCount() {
return clients.size();
}
}
创建配置文件
创建config文件夹及WebSocketConfig.java
@configurature
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
Vue
创建websocket类
用ws.ts封装websocket
class WS {
ip: string
port: string
closure: Function
ws: WebSocket
constructor (ip: string, port: string) {
thie.ip = ip
this.port = port
this.ws = new WebSocket('ws://' + ip + ':' + port)
this.ws.open = function () {
console.log('acquiring data')
}
this.ws.onmessage = function (ev: any) {
console.log('收到spring消息', ev.data)
}
this.ws.onclose = function (ev: any) {
alert('connection closed!')
}
this.ws.onerror = function (ev: any) {
alert('connection error!')
}
this.closure = function () {
this.ws.close()
}
}
}
初始化
<script setup lang='ts'>
import { onMounted, onUnmounted } from 'vue'
import { WS } from '@/utils/ws'
let ws: WS
onMounted(() => {
ws = new WS('192.168.1.200', '8891/websocket/test')
})
onUnmounted(() => {
ws.closure()
})
</script>
测试
连接与通信
vue
springboot
断开连接
vue
springboot
参考资料
【web系列十六】idea下使用Maven搭建spring boot开发环境_Nicholson07的博客-CSDN博客
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/100771.html