53 lines
1.7 KiB
TypeScript
53 lines
1.7 KiB
TypeScript
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) {
|
|
console.log("Creating websocket server")
|
|
wss = new WebSocketServer({ server: event.node.res.socket?.server })
|
|
wss.on("connection", function (socket) {
|
|
console.log("Client connected")
|
|
socket.send("connecte")
|
|
socket.on("message", function (message) {
|
|
wss.clients.forEach(function (client) {
|
|
console.log("Client", client)
|
|
client.send('message')
|
|
if (client == socket && client.readyState === WebSocket.OPEN) {
|
|
clients.push({
|
|
id: message.toString(),
|
|
send: (data: string) => client.send(data),
|
|
readyState: client.readyState,
|
|
})
|
|
global.clients = clients
|
|
}
|
|
})
|
|
})
|
|
socket.on("close", function () {
|
|
clients = clients.filter((client) => client.readyState !== WebSocket.CLOSED)
|
|
global.clients = clients
|
|
console.log("Client disconnected")
|
|
})
|
|
socket.on("error", function (error) {
|
|
console.log("Error", error)
|
|
})
|
|
socket.on("pong", function (data) {
|
|
console.log("Pong", data)
|
|
})
|
|
global.wss = wss
|
|
})
|
|
}
|
|
})
|