简体   繁体   English

带有Angular 2事件的Socket.io会触发两次

[英]Socket.io with Angular 2 Event fires twice

I am using Socket.io 1.0 with Angular 2.0.0-rc.5 and Express 4. Emit in bin/www fires as many times as the users connected, So rather than one broadcast they get multiple and only the first event has the message. 我正在使用Socket.io 1.0与Angular 2.0.0-rc.5和Express 4.在bin / www fires中发送的次数与用户连接的次数相同,因此,而不是一次广播,他们得到多个,只有第一个事件有消息。 Using console.log in just about everywhere i can tell it only produces multiple logs inside bin/www socket.on('add-message') 在几乎无处不在的地方使用console.log我只能在bin / www socket.on('add-message')中生成多个日志

bin/www 斌/ WWW

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('a2-test:server');
var http = require('http');

/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '4000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

var io = require('socket.io')(server);

io.on('connection', function (socket) {

  console.log('a user connected', socket.id);

  socket.on('add-message', (message) => {
    console.log('broadcast', socket.id, message)
    io.emit('message', {text: message})
  });
});

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

chat.component.ts chat.component.ts

export class ChatComponent implements OnInit, OnDestroy {
    messages = [];
    connection;
    message;

    constructor(private chatService: ChatService) {

     }

    sendMessage() {
        this.chatService.sendMessage(this.message);
        this.message = '';
    }

    ngOnInit() {
        this.connection = this.chatService.getMessages().subscribe(
            (msg) => {
                this.messages.push(msg)
            });
    }

    ngOnDestroy() {
        this.connection.unsubscribe();
    }
}

chat.service.ts chat.service.ts

import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
import * as io from 'socket.io-client';

export class ChatService {
  private url = 'http://localhost:4000';  
  private socket;

  sendMessage(message){
    this.socket.emit('add-message', message);
  }

  getMessages() {
    let observable = new Observable(observer => {
      this.socket = io(this.url);

      this.socket.on('message', (data) => {
        observer.next(data);    
      });

      return () => {
        this.socket.disconnect();
      };  
    })     
    return observable;
  }  
}

chat.template.html chat.template.html

<div class="col-lg-8 well" style="min-height: 200px">
    <ul class="col-lg-12">
        <li *ngFor="let message of messages">
            {{message.text}}
        </li>
    </ul>
</div>
<div class="col-lg-4 well">
    <input [(ngModel)]="message" class="form-control">
    <br>
    <button class="btn btn-primary col-lg-4" (click)="sendMessage()">Send</button>
</div>

I managed to solve the problem if anyone is stuck on the same issue. 如果有人遇到同样的问题,我设法解决了这个问题。 I was running two servers. 我正在运行两台服务器。 lite-server for the Angular 2 app and nodemon. 用于Angular 2 app和nodemon的lite-server。 Lite server and Browser sync were causing the problem. Lite服务器和浏览器同步导致了问题。 Running the project through one server solved the problem. 通过一台服务器运行项目解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM