我正试图从以下位置创建websocket连接
python.py
到
index.vue
.
我无法在页面加载时建立连接。
索引.vue->model.post.ts->python.py->
(websocket)
->index.vue
我想从发送数据
python.py
而在过程中
index.vue
客户端提供实时更新,这就是我遇到的问题。
参考YouTube视频
https://www.youtube.com/watch?v=d-LSN-xo6N4
引用GitHub
https://github.com/adityar15/nuxt3socket/tree/master
"@types/uuid": "^9.0.4",
"@types/ws": "^8.5.6"
/index.vue
<div>message: {{ message }}</div>
import { v4 as uuid } from "uuid";
const uid = uuid()
const message = ref<string>("")
const { $socket } = useNuxtApp()
onMounted(() => {
$socket.onopen = () => {
console.log('WebSocket is open now.')
localStorage.setItem(`connection-${uid}`, uid)
$socket.send(uid)
}
// $socket.onmessage = ({ data }: any) => {
// console.log("data:", data)
// message.value = data
// }
$socket.onclose = function () {
console.log("disconnected")
}
/插件/webocket.client.ts
export default defineNuxtPlugin(() => {
if (process.server) return
const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:"
let socket = new WebSocket(`${wsProtocol}//${window.location.host}`)
return {
provide: {
socket,
},
}
})
/服务器/中间件/socket.ts
import WebSocket, { WebSocketServer } from "ws"
type Client = {
id: string
send: (message: string) => void
readyState: number
}
declare global {
var wss: WebSocketServer
//var clients: Client[]
}
let wss: WebSocketServer
//let clients: Client[] = []
export default defineEventHandler((event) => {
if (!global.wss) {
wss = new WebSocketServer({ server: (event.node.res.socket as any)?.server })
wss.on("connection", function (socket) {
console.log('New connection established.')
socket.send("connected")
socket.on("error", function (error) {
console.log(`Socket Error: ${error}`);
});
wss.on("error", function (error) {
console.log(`WebSocket Server Error: ${error}`);
});
global.wss = wss
}
})
data.py
pip install websocket-client
from websocket import create_connection
ws_url = 'ws://localhost:3000'
print(f"Attempting to connect to {ws_url}")
ws = create_connection(ws_url)
print("WebSocket connection established.")
def send_progress_data(data):
print('sending progress data...')
message = f"data: {data}"
ws.send(message)
print(f"Sent: {message}")
...
我没有收到任何错误消息,但没有建立连接