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.2KB

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