angular中使用Socket.io实例代码

网友投稿 239 2023-05-10


angular中使用Socket.io实例代码

服务端(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.ooYgEPn('disconnect', function(){

console.log('user disconnected');

});

socket.onoYgEP('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.socoYgEPket.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: `

{{message.text}}

`,

providers: [ChatService]

})

export class ChatComponent implements OnInit, OnDestroy {

messages = [];

connection;

message;

constructor(private chatService:ChatService) {}

sendMessage(){

this.chatService.sendMessage(oYgEPthis.message);

this.message = '';

}

ngOnInit() {

this.connection = this.chatService.getMessages().subscribe(message => {

this.messages.push(message);

})

}

ngOnDestroy() {

this.connection.unsubscribe();

}

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Java字母大小写转换的方法
下一篇:Struts2实现上传单个文件功能
相关文章

 发表评论

暂时没有评论,来抢沙发吧~