kcpServer.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. const kcp = require('./build/Release/kcp')
  2. const dgram = require('dgram');
  3. const server = dgram.createSocket('udp4');
  4. /**
  5. * @params ID 通信id: 110
  6. * @pramss port 端口默认: 41234
  7. * @params type 工作模式: 急速1 | 默认普通0
  8. */
  9. class KcpServer {
  10. constructor(ID = 110, port = 41234, type = 0) {
  11. this.ID = ID
  12. this.port = port
  13. this.type = type
  14. this.clients = {}
  15. this.timer = null
  16. this.output = (data, size, context) => server.send(data, 0, size, context.port, context.address)
  17. this.Init()
  18. }
  19. // init
  20. Init() {
  21. server.bind(this.port);
  22. server.on('listening', () => {
  23. console.log(66,JSON.stringify(server));
  24. const address = server.address();
  25. console.log(`server listening ${address.address} : ${address.port}`);
  26. const time = this.type ? 10 : 50
  27. this.timer = setInterval(() => {
  28. for (const k in this.clients) {
  29. const kcpobj = this.clients[k];
  30. kcpobj.update(Date.now());
  31. const recv = kcpobj.recv();
  32. if (recv) {
  33. console.log(`server recv ${recv} from ${kcpobj.context().address}:${kcpobj.context().port}`);
  34. kcpobj.send('RE-' + recv);
  35. }
  36. }
  37. }, time);
  38. })
  39. server.on('message', (msg, rinfo) => {
  40. const k = rinfo.address + '_' + rinfo.port;
  41. if (undefined === this.clients[k]) {
  42. const context = {
  43. address: rinfo.address,
  44. port: rinfo.port
  45. };
  46. this.clients[k] = new kcp.KCP(this.ID, context);
  47. if(this.type){
  48. this.clients[k].nodelay(1, 10, 2, 1);
  49. }else{
  50. this.clients[k].nodelay(0, 50, 0, 0);
  51. }
  52. this.clients[k].output(this.output);
  53. }
  54. this.clients[k].input(msg);
  55. })
  56. server.on('error', er => {
  57. clearInterval(this.timer)
  58. this.clients = {}
  59. this.timer = null
  60. })
  61. }
  62. }
  63. new KcpServer()