1、创建 webSocket.service.ts 服务。
import {HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Subject} from 'rxjs';
import {BaseService} from "./base.service";
/**
* websocket服务
*/
@Injectable()
export class WebSocketService extends BaseService{
ws: WebSocket;
url: string;
memberId: string;
private heart: Subject<any> = new Subject<any>();//监听心跳
private message: Subject<any> = new Subject<any>();//监听心跳
constructor(public http: HttpClient) {
super();
}
setMember(memberId: string) {
this.memberId = memberId;
this.url = this.BASE_WSURL;
}
getMember() {
return this.memberId;
}
/**
* 创建websocket
* @param url
*/
createObservableScoket(url: string): Observable<any> {
this.ws = new WebSocket(this.BASE_WSURL);
return new Observable(observer => {
// 返回成功时执行的方法
this.ws.onmessage = event => observer.next(event.data);
// 返回错误时执行的方法
this.ws.onerror = event => {
console.log("websocket异常:" + event);
// this.initializeWebSocket()
};
// 关闭websocket流时执行的方法
// this.ws.onclose = event => observer.complete();
this.ws.onclose = event => {
console.log("服务器关闭了链接");
// this.initializeWebSocket()
};
});
}
/**
*
* @param msg 发送消息
*/
sendMessage(msg: any) {
msg.memberId = this.memberId;
this.ws.send(JSON.stringify(msg));
}
/**
* 初始化websocekt
*/
initializeWebSocket() {
this.createObservableScoket(this.url).subscribe(
data => {
this.analysisMessage(data);
},
error => {
console.log("websoclet异常:" + error);
},
() => console.log("webSocket已结束!")
);
}
/**
* 返回心跳
*/
getHeart(): Observable<any> {
return this.heart.asObservable();
}
/**
* 返回消息
*/
getMessage(): Observable<any> {
return this.message.asObservable();
}
/**
* 关闭websocket
*/
closeWebSocket() {
this.ws.close();
}
/**
* 发送心跳
*/
pong() {
// this.ws.send(AppApi.api_websocket_heart);
}
/**
* 解析返回值
*/
analysisMessage(message: any) {
// let messageJson = JSON.parse(message);
let messageJson = message;
if (messageJson.type == 0) {
this.heart.next(messageJson);
} else {
this.message.next(messageJson);
}
}
}
2、在app.module 注册websocket 服务
3、在需要用的的组件里发送msg
/**
* 发送消息
* @param event
*/
this.websocket.sendMessage(data: {});
this.getMessage()