2016-08-30 288 views
1

我使用的是Socket.io 1.0與Angular 2.0.0-rc.5和Express 4.在bin/www中發射的次數與用戶連接次數一樣多,所以不是一次廣播他們得到多個,只有第一個事件有消息。在幾乎任何地方使用的console.log我可以告訴它只能產生斌/ WWW socket.on內多個日誌( '附加信息')Socket.io與角2事件兩次觸發

斌/ 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

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

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

<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> 

回答

0

我管理,如果有人被卡在同一個問題來解決問題。 我正在運行兩臺服務器。適用於Angular 2應用程序和nodemon的lite-server。 精簡版服務器和瀏覽器同步引起了問題。通過一臺服務器運行項目解決了這個問題。