You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Server.ts 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { Server, Socket } from "socket.io"
  2. import { Server as httpServer } from "http"
  3. import * as U from '../Utils'
  4. import * as T from '../Types'
  5. import socketio = require('socket.io')
  6. import middleware = require('socketio-wildcard');
  7. const defaultConfig : socketio.ServerOptions = {
  8. cookie: false,
  9. path: '/socket.io',
  10. }
  11. export class PromiseIO {
  12. io?: Server
  13. httpServer: httpServer
  14. private listeners: { [eventName in string]: ((...args: any) => void)[] } = {
  15. socket: [],
  16. connect: []
  17. }
  18. attach(httpServer: httpServer, options: socketio.ServerOptions = defaultConfig) {
  19. if(options.path && !options.path.startsWith('/')){
  20. options.path = "/"+options.path
  21. }
  22. this.httpServer = httpServer
  23. this.io = socketio(httpServer, options)
  24. this.io!.use(middleware())
  25. this.io!.on('connection', (clientSocket: Socket) => {
  26. clientSocket['address'] = clientSocket.handshake.headers["x-real-ip"] || clientSocket.handshake.address
  27. const pioSock = U.makePioSocket(clientSocket)
  28. this.listeners['socket'].forEach(listener => listener(pioSock))
  29. this.listeners['connect'].forEach(listener => listener(pioSock))
  30. /*
  31. pioSock.on('error', ()=>console.log('error'));
  32. pioSock.on('connect_timeout', ()=>console.log('connect_timeout'))
  33. pioSock.on('disconnect', ()=>console.log('disconnect'))
  34. pioSock.on('reconnect', ()=>console.log('reconnect'))
  35. pioSock.on('reconnect_attempt', ()=>console.log('reconnect_attempt'))
  36. pioSock.on('reconnecting', ()=>console.log('reconnecting'));
  37. pioSock.on('reconnect_failed', ()=>console.log('reconnect_failed'));
  38. pioSock.on('reconnecting', ()=>console.log('reconnecting'));
  39. */
  40. })
  41. }
  42. listen(port: number) {
  43. this.httpServer!.listen(port)
  44. }
  45. on(eventName: string, listener: T.AnyFunction) {
  46. if (this.listeners[eventName] == null) {
  47. this.listeners[eventName] = []
  48. }
  49. this.listeners[eventName].push(listener)
  50. }
  51. close = () => {
  52. if(this.io){
  53. this.io.engine.ws.close()
  54. this.io.close()
  55. this.io = undefined
  56. }
  57. }
  58. }