4 changed files with 61 additions and 36 deletions
@ -1,11 +1,50 @@ |
|||
import { Server } from "ws"; |
|||
import { Datagram } from "../types/wsTypes"; |
|||
|
|||
export function wsSend(wss: Server, data: Datagram) { |
|||
// 广播消息给所有连接的客户端
|
|||
wss.clients.forEach(client => { |
|||
if (client.readyState === client.OPEN) { |
|||
client.send(JSON.stringify(data)); |
|||
} |
|||
}); |
|||
import http from 'http'; |
|||
import { Server, WebSocket } from 'ws'; |
|||
import { Datagram } from '../types/wsTypes'; |
|||
|
|||
export class WsProxy { |
|||
public static server: Server; |
|||
|
|||
private static actionsWhenClientConnect: ((ws: WebSocket) => void)[] = []; |
|||
|
|||
static addActionForClientConnect(act: (ws: WebSocket) => void) { |
|||
this.actionsWhenClientConnect.push(act); |
|||
} |
|||
static init(server: http.Server) { |
|||
this.server = new Server({ server }); |
|||
this.onConnection(); |
|||
} |
|||
|
|||
private static onConnection() { |
|||
this.server.on('connection', ws => { |
|||
console.log('Client connected'); |
|||
// ws.send("Welcome to the WebSocket server!");
|
|||
// ws.on("message", message => {
|
|||
// console.log(`Received message: ${message}`);
|
|||
// wss.clients.forEach(client => {
|
|||
// if (client.readyState === ws.OPEN) {
|
|||
// client.send(message.toString());
|
|||
// }
|
|||
// });
|
|||
// });
|
|||
this.actionsWhenClientConnect.forEach(act => act(ws)); |
|||
|
|||
ws.on('close', () => { |
|||
console.log('Client disconnected'); |
|||
}); |
|||
}); |
|||
} |
|||
|
|||
public static send(data: Datagram, ws?: WebSocket) { |
|||
// DeviceContext
|
|||
if (ws) { |
|||
ws.send(JSON.stringify(data)); |
|||
} else { |
|||
this.server.clients.forEach(ws => { |
|||
if (ws.readyState === ws.OPEN) { |
|||
ws.send(JSON.stringify(data)); |
|||
} |
|||
}); |
|||
} |
|||
} |
|||
} |
Write
Preview
Loading…
Cancel
Save
Reference in new issue