如何使用Express Controller中的socket.io事件从客户端接收数据?

时间:2018-09-28 19:47:11

标签: node.js typescript express socket.io angular6

我正在使用带有TypeScript的Express框架:

我想使用Socket IO在登录时获取客户端位置,因此在客户端,我在登录页面上进行了一次send事件。在服务器端,我尝试将套接字事件集成到登录控制器中,该事件在响应发送回客户端之前放置,但是我已经登录并单击退出后,服务器事件触发了按钮,该按钮使我再次登录页面(这是我从console.log(data)在服务器端收到位置消息的时刻。)

这是身份验证控制器文件(auth.controller.ts)的样子:

 import { io } from '../server/https';
 ....
 ..

 public authenticate(req: Request, res: Response) {
   if(req.body.email && req.body.password) {
     ....
     ..

     io.on('connection', (socket: SocketIO.Socket) => {
       console.log('New Socket Connected!');
       socket.on('client-location', (data) => {
         console.log(data);
       });
       socket.on('disconnect', (reason) => {
         console.log(reason);
       });
     });
     res.status(200).json({
       resType: 'success',
       token: 'Bearer ' + token,
       userId: user.id,
       message: 'Authenticated.',
       loginNumber: result.session.length
     });

   };
    ....
    ..

}

auth.controller.ts中的{io}导入是从https.ts文件导出的io常量。 以下是https.ts文件:

 import socketIO from 'socket.io';
 import HTTPS from 'https';

 import app from '../app/index';
 ....
 ..

 const options = {
     cert: fs.readFileSync(path.resolve('../../../certificates/ca.crt')),
     key: fs.readFileSync(path.resolve('../../../certificates/ca.key'))
 }

 export const server = HTTPS.createServer(options, app)
 .listen(process.env.HTTP_SERVER_PORT, () => {
     console.log(`Platform Server is running from 
  ${process.env.HTTP_SERVER_HOST}, port: ${process.env.HTTP_SERVER_PORT}`);
 });

 export const io = socketIO.listen(server);

有些东西不同步,我听不到。

客户端是用Angular 6编写的,发出事件的组件如下:

import { Component, OnInit } from '@angular/core';
import { LoginService } from '../../services/login.service';
import { Router } from '@angular/router';
import * as io from 'socket.io-client';

import { env } from '../../../../../environments/environment';

@Component({
  selector: 'login-form',
  templateUrl: './login-form.component.html',
  styleUrls: ['./login-form.component.css']
})

export class LoginFormComponent implements OnInit {

  public positionOptions = {
      enableHighAccuracy: true,
      maximumAge: 0
  };
  public LoginFormModel: any = {};
  private URL = `${env.WS_SERVER_URL}:${env.HTTP_SERVER_PORT}`;
  private socket;

  constructor(private loginController: LoginService,
   private router: Router) { 
    this.socket = io(this.URL);
  }

  ngOnInit() {}

  public emitLocation() {
      navigator.geolocation.getCurrentPosition(position => {
        const { latitude: lat, longitude: lng } = position.coords;
        console.log({ lat, lng });
        this.socket.emit('client-location', { lat, lng });
      },
      err => {
        console.log(err);
      }, this.positionOptions);
  }

  loginEvent() {
      this.loginController.login(this.LoginFormModel.email.value, 
      this.LoginFormModel.password.value)
      .subscribe(
         result => {
           this.loginController.createSession('token', result.token);
           this.emitLocation();
           this.router.navigate(['user/profile']);
         },
         err => {
         console.log(err);
         });
  }
}

0 个答案:

没有答案