app.component.ts
/**
* 监听心跳
*/
getHeart(){
let request=this.websocket.getHeart().subscribe(result=>{
this.websocket.pong();
});
}
//初始化方法
ngOnInit(){
// let user=this.appCfg.getUserInfo();
// console.log(user);
// if(null==user || undefined==user){
// return;
// }
this.websocket.setMember("152402270655899655862");
this.websocket.initializeWebSocket();
this.getHeart();
}
component chat.ts
import { Component,Input,Output, ViewChild,EventEmitter } from '@angular/core';
import { GroupProvider } from '../../providers/group/group'
import { WebSocketProvider } from '../../providers/web-socket/web-socket';
@Component({
selector: 'chat',
templateUrl: 'chat.html'
})
export class ChatComponent {
totalPage:number=1;
page:number=1;
recordList=[];
msg={text: "", memberId: "", type: 1, groupId: ""};
constructor(private groupProvider:GroupProvider,private websocket:WebSocketProvider) {
this.getMessage();
}
/**
* 获取聊天记录
*/
getRecord(){
let request=this.groupProvider.getGroupRecord(this.msg.groupId,this.page).subscribe(result=>{
this.recordList=result['data']['list'];
this.totalPage=result['data']['totalPage'];
request.unsubscribe();
});
}
/**
* 发送消息
* @param event
*/
sendMessage(event){
if("Enter"==event.key){
this.websocket.sendMessage(this.msg);
}
}
/**
* 监听消息
*/
getMessage(){
let request=this.websocket.getMessage().subscribe(result=>{
this.recordList.push(result);
});
}
}
page chat.module.ts 中imports ComponentsModule
chat.ts
import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ChatComponent } from '../../components/chat/chat';
/**
* Generated class for the ChatPage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-chat',
templateUrl: 'chat.html',
})
export class ChatPage {
@ViewChild(ChatComponent) ChatComponent:ChatComponent;
title:string;
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.title=this.navParams.get("title");
}
ionViewDidLoad(){
this.ChatComponent.msg.groupId=this.navParams.get("groupId");
this.ChatComponent.getRecord();
}
goGroupMember(){
this.navCtrl.push('GroupMembersPage',{groupId:this.ChatComponent.msg.groupId})
}
/**
* 下拉
* @param refresher
*/
doRefresh(refresher) {
if(this.ChatComponent.page>1){
this.ChatComponent.page--;
}
this.ChatComponent.getRecord();
setTimeout(() => {
refresher.complete();
}, 1000);
}
/**
* 上拉
* @param infiniteScroll
*/
doInfinite(infiniteScroll) {
if(this.ChatComponent.page<this.ChatComponent.totalPage){
this.ChatComponent.page++;
}
this.ChatComponent.getRecord();
setTimeout(() => {
infiniteScroll.complete();
}, 1000);
}
}
providers web-socket.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
import { NgSwitchCase } from '@angular/common';
import { AppConfig,AppApi } from '../../app/config';
import { Subject } from 'rxjs';
/**
* websocket服务
*/
@Injectable()
export class WebSocketProvider {
ws: WebSocket;
url:string;
memberId:string;
private heart: Subject<any> = new Subject<any>();//监听心跳
private message: Subject<any> = new Subject<any>();//监听心跳
constructor(public http: HttpClient,private appCfg: AppConfig) {
}
setMember(memberId:string){
this.memberId=memberId;
this.url=AppApi.api_websocket_url+this.memberId;
}
getMember(){
return this.memberId;
}
/**
* 创建websocket
* @param url
*/
createObservableScoket(url: string): Observable<any> {
this.ws = new WebSocket(url);
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);
if(messageJson.type==0){
this.heart.next(messageJson);
}else{
this.message.next(messageJson);
}
}
}
在app.component中启动websocket服务,监听心跳,在chat组件中监听message,websocket操作的代码都在websocket服务中。