springboot
pom.xml引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
创建配置类
package com.example.demo1.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
//自动注册了@ServerEndpoint
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
创建接收消息的路径
package com.example.demo1.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@ServerEndpoint(value = "/test")
@Component
public class TestController {
//存储每一个客户端对象
private static Map<String,Session> users=new ConcurrentHashMap<>();
/**
* 建立连接的时候 触发
*/
@OnOpen
public void onOpen(Session session){
log.info("和服务端建立连接了");
//将当前对象存储到map中 用户写死
users.put("1",session);
}
@OnMessage
public void onMessage(String message,Session session){
log.info("接收到客户端发过来的消息:{}",message);
//给客户端发送收到
try {
session.getBasicRemote().sendText("服务器收到消息了,给客户端发送收到");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@OnClose
public void onClose(Session session){
log.info("连接被关闭了");
}
//如果你有多个用户的话 可以将消息转发给所有用户 做群聊
private void send(String msg){
for (Map.Entry<String, Session> x : users.entrySet()) {
Session t=x.getValue();
try {
//异步发送文本消息
t.getBasicRemote().sendText(msg);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
Vue3
修改App.vue
<template>
<input v-model="msg"/>
<button @click="send">给服务器发消息</button>
</template>
<script setup lang="ts">
import {onMounted,ref} from 'vue'
//消息内容
let msg=ref('')
//创建对象 绑定接口
let ws=new WebSocket("ws://localhost:8080/test");
//初始化
let init=()=>{
//监听连接
ws.onopen=open
//监听错误信息
ws.onerror=error
//监听消息
ws.onmessage=getMsg
//断开连接
ws.close=close
}
let open=()=>{
console.log('连接成功')
}
let error=()=>{
console.log('连接错误')
}
let getMsg=(message)=>{
//接收服务器传过来的消息
console.log('收到消息:'+message.data)
}
let close=()=>{
console.log('连接关闭')
}
//发送消息
let send=()=>{
ws.send(msg.value)
}
//生命周期 挂载
onMounted(() => {
init();
})
</script>
测试
输入内容,给服务器发送消息,并且接收服务器发送过来的消息
服务器接收到客户端发过来的消息,并发送消息给客户端