socket.ts 784 B

123456789101112131415161718192021222324252627282930
  1. // socket.ts
  2. import { Server, Socket } from 'socket.io';
  3. import * as http from 'http';
  4. import chalk from 'chalk';
  5. import { WS_EVENTS } from './utils';
  6. export let io: Server;
  7. export let clients = new Map<string, Socket>();
  8. export function initWebSocket(server: http.Server) {
  9. io = new Server(server, {
  10. cors: {
  11. origin: '*',
  12. methods: ['GET', 'POST'],
  13. },
  14. });
  15. io.on('connection', (socket: Socket) => {
  16. // register client
  17. socket.on(WS_EVENTS.REGISTER, (clientId: string) => {
  18. clients.set(clientId, socket);
  19. console.info(chalk.green(`ws client connected ${clientId}`));
  20. socket.on('disconnect', () => {
  21. console.info(chalk.green(`ws client disconnected ${clientId}`));
  22. clients.delete(clientId);
  23. });
  24. });
  25. });
  26. }