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.

Backend.ts 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. 'use strict'
  2. import http = require('http');
  3. import bsock = require('bsock');
  4. import * as T from './Types';
  5. import * as U from './Utils';
  6. import * as I from './Interfaces';
  7. import * as R from './Responses';
  8. export {
  9. T as Types,
  10. U as Utils,
  11. I as Interfaces,
  12. R as Responses
  13. }
  14. export class Server{
  15. private ws = http.createServer()
  16. private io = bsock.createServer()
  17. constructor(
  18. private port:number,
  19. private exporters: I.Exporter[] = [],
  20. private conf: T.SocketConf = {
  21. errorHandler: (socket:I.Socket) => (error:any) => { socket.destroy(); console.error(error) },
  22. closeHandler: (socket:I.Socket) => () => { console.log("Socket closing") },
  23. connectionHandler: (socket:I.Socket) => { console.log("New websocket connection in port "+socket.port)},
  24. visibility: "127.0.0.1"
  25. }
  26. ){
  27. this.startWebsocket()
  28. }
  29. private startWebsocket(){
  30. try{
  31. this.io.attach(this.ws)
  32. this.io.on('socket', (socket:I.Socket) => {
  33. socket.on('error', this.conf.errorHandler(socket))
  34. socket.on('close', this.conf.closeHandler(socket))
  35. if(this.conf.visibility === "127.0.0.1")
  36. this.initRPCs(socket)
  37. else
  38. this.initPublicRPCs(socket)
  39. })
  40. this.ws.listen(this.port, this.conf.visibility)
  41. }catch(e){
  42. //@ts-ignore
  43. this.errorHandler(undefined)("Unable to connect to socket")
  44. }
  45. }
  46. protected initRPCs(socket:I.Socket){
  47. socket.hook('info', () => rpcInfos)
  48. const rpcInfos:T.ExtendedRpcInfo[] = [
  49. ...this.exporters.flatMap(exporter => U.rpcHooker(socket, exporter))
  50. ]
  51. }
  52. protected initPublicRPCs(socket:I.Socket){
  53. socket.hook('info', () => rpcInfos)
  54. const rpcInfos:T.ExtendedRpcInfo[] = [
  55. ...this.exporters.flatMap(exporter => U.rpcHooker(socket, exporter))
  56. ]
  57. }
  58. }