相思资源网 Design By www.200059.com

服务端(nodeJs/express):

let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);

io.on('connection', (socket) => {
 console.log('user connected');
 
 socket.on('disconnect', function(){
  console.log('user disconnected');
 });
 
 socket.on('add-message', (message) => {
  io.emit('message', {type:'new-message', text: message});  
 });
});

http.listen(5000, () => {
 console.log('started on port 5000');
});

客户端,创建一个ChatService

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

export class ChatService {
 private url = 'http://localhost:5000'; 
 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;
 } 
}

ChatComponent

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Control }      from '@angular/common';
import { ChatService }    from './chat.service';

@Component({
 moduleId: module.id,
 selector: 'chat',
 template: `<div *ngFor="let message of messages">
           {{message.text}}
          </div>
          <input [(ngModel)]="message" /><button (click)="sendMessage()">Send</button>`,
 providers: [ChatService]
})
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(message => {
   this.messages.push(message);
  })
 }
 
 ngOnDestroy() {
  this.connection.unsubscribe();
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

标签:
angularjs,socket.io,angular2,socket.io,angular,socket.io

相思资源网 Design By www.200059.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
相思资源网 Design By www.200059.com

评论“angular中使用Socket.io实例代码”

暂无angular中使用Socket.io实例代码的评论...