使用Socket.io与typescript并做出反应

时间:2018-04-15 10:47:28

标签: reactjs typescript websocket socket.io

我正在努力在Node应用程序和React应用程序之间建立websocket连接。但是我似乎无法使用函数this.io.on()在类socket中的listen方法中运行。服务器记录" listen"但没有'在端口%s上连接客户端。',this.port。我的问题是为什么它没有?

服务器应用程序中的文件index.ts。

/// <reference types="@types/node" />

// Imports.
import * as http from 'http';
import App from './App';
import * as socketIo from 'socket.io';
import { SocketIO, Server } from 'socket.io';

const port = process.env.PORT || 3000;
const server = http.createServer(App);

// Start the server.
App.listen(port, (err) => {
  if (err) {
  return console.error(err);
}
  new socket(server);

  return console.log(`Server is listening on ${port}`);
});


class socket {

  private server: Server;
  private io: SocketIO.Server;
  private port = 3000;

  constructor(server) {
      this.createServer(server);
      this.sockets();
      this.listen();
  }

  private createServer(server: any): void {
      this.server = server;
  }

  private sockets(): void {
      this.io = socketIo(this.server);
  }

  private listen(): void {
      console.log("listen");
      this.io.on('connect', (socket: any) => {
          console.log('Connected client on port %s.', this.port);
          socket.on('message', (m: any) => {
              console.log('[server](message): %s', JSON.stringify(m));
              this.io.emit('message', m);
          });

          socket.on('disconnect', () => {
              console.log('Client disconnected');
          });
      });
  }
}

1 个答案:

答案 0 :(得分:0)

您可能错误this导致this.io成为undefined

修复

使用arrow function

  private listen = (): void => { // ARROW
      console.log("listen");
      this.io.on('connect', (socket: any) => {