以下代码是使用vue3 和Springboot 通过 websocket实现前后端通信,但是失败,请指出错误原因并且更正代码
<script setup>
import {ref} from "vue";
const message=ref()
let socket;
socket = new WebSocket("ws/webSocket");
socket.onopen = function(event) {
console.log(event.data);
};
socket.onmessage = function(event) {
console.log(event.data);
};
socket.onerror = function(error) {
console.log("WebSocket Error: " + error);
}
function senMessage() {
if (socket.readyState===1) {
socket.send(message)
}
}
</script>
<template>
<div class="MyBody1">
<input type="text" v-model="message">
<button @click="senMessage">sent</button>
</div>
</template>
<style scoped>
</style>
devServer:{
allowedHosts: "all",
proxy: {
'/spring': {
target: 'http://localhost:8081',
changeOrigin: true,
pathRewrite: { // pathRewrite 的作用是把实际Request Url中的'/api'用""代替
'^/spring': ""
}
},
'/ws': {
target: 'ws://http://localhost:8081',
ws: true,
changeOrigin: true,
// logLevel: 'debug' // 可选,用于调试代理连接
pathRewrite: { // pathRewrite 的作用是把实际Request Url中的'/api'用""代替
'^/ws': ""
}
},
},
},
package org.example.halospring.HaloSpring.Service.WebsocketService;
import jakarta.servlet.http.HttpSession;
import jakarta.websocket.*;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
@ServerEndpoint("/webSocket")
public class WebsocketImple {
public static int number=0;
@OnOpen
public void onOpen(Session session, HttpSession httpSession) throws IOException {
number++;
System.out.println("第"+number+"个用户登录");
session.getAsyncRemote().sendText("第"+number+"个用户登录");
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
System.out.println(message);
}
@OnClose
public void onClose(Session session) {
session.getAsyncRemote().sendText("关闭");
number--;
System.out.println("用户关闭");
}
@OnError
public void onError(Throwable error) {
System.err.println("WebSocket Error: " + error);
}
}