Tuesday 14 March 2017

Angular2 Socket.io private message

I want to sent a private message to an user. I am able to sent the message but what is the best way to deliver the message to a specific user? I passed the userId over the sendMessage() method and I am getting the message over the getMessages() method.

messages.component.html

<div class="stick" style="background-color:#F5F5F5;">
  <h5>Messages:</h5>

<ul>
<li *ngFor="let msg of msgs">

</li>
</ul>

<input #mm/>
<button (click)="sendMessage(mm.value); mm.value=''">Send</button>
</div>

messages.component.ts

import { Component,Input,OnInit,Output,EventEmitter,HostListener,ElementRef, NgZone} from "@angular/core";

import * as sio from 'socket.io-client';
import { Observable } from 'rxjs/Observable';
@Component({

    selector: "messages",
    templateUrl: './messages.component.html'

})

export class MessagesComponent implements  OnInit{

             socket: SocketIOClient.Socket;
             private url = 'http://localhost:4200';
             connection;
             messages = [];




            constructor(private _zone: NgZone, public http: Http) {
                 this.socket = sio(this.url);
           }





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

        }




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

getMessages() {
    let observable = new Observable(observer => {

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

}

}

www.ts

import { app } from '../app';
import * as http from 'http';




/**
 * Get port from environment and store in Express.
 */
const port = normalizePort(process.env.PORT || 3000);
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

let io = require('socket.io').listen(server);



io.on('connection', (socket) => {

  socket.on('disconnect', function(){
    console.log('user disconnected');
  });

  socket.on('add-message', (message) => {
    io.emit('message', {type:'new-message', text: message});
  });
});
/**
 * Listen on provided port, on all network interfaces.
 */

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



via Tony

No comments:

Post a Comment