1、建立service文件
ng g service share/web-socket --app
2、web.sockect.service.ts 文件如下
import {Injectable} from '@angular/core';
import * as io from 'socket.io-client';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class WebSocketService {
private ws: any;
private message: Subject<any> = new Subject<any>(); // 消息列表
constructor() {
}
// 连接后台socket
connetSocket(url) {
this.ws = io(url);
this.ws.on('connect_error', (error) => { // 连接失败
console.log('connect_error');
});
this.ws.on('reconnecting', (timeout) => { // 重连次数
if (timeout === 3) {
this.ws.close();
}
});
this.ws.on('message', (data) => {
this.analysisMessage(data);
});
}
analysisMessage(message) {
//const messagejson = JSON.parse(message);
this.message.next(message);
}
getMessage(): Observable<any> {
return this.message.asObservable();
}
}
3组件文件
import {Component, OnInit} from '@angular/core';
import {_HttpClient} from '@delon/theme';
import {WebSocketService} from '@shared/web-socket.service';
@Component({
selector: 'app-messagelist',
templateUrl: './messagelist.component.html',
providers: [WebSocketService]
})
export class MessagelistComponent implements OnInit {
public message = [];
constructor(
private http: _HttpClient,
private messageService: WebSocketService
) {
}
ngOnInit() {
this.connect();
}
connect() {
this.messageService.connetSocket('http://localhost:8086/message');
}
getMessage() {
this.messageService.getMessage().subscribe(result => {
console.log(result);
});
}
}
4服务端文件
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8086);
console.log('服务正常启动')
//警告:app.listen(80)在这里不起作用!
app.get('/',function(req,res) {
res.sendFile(__dirname + '/ index.html');
});
const messageServer=io.of('message')
messageServer.on('connection',function(socket) {
console.log('链接')
const message=[{ 'value':'1111' },{'value':'2222'}]
setInterval(()=>{
message.push({
'value':'3333'
})
socket.emit('message',message)
},1000)
socket.on('my other event',function(data) {
console.log(data)
}
)
})