在angular7中,cli已经自动配置了websocket,不用再次进行安装
第一种websocket,没使用订阅,有断线重连的功能
1.创建一个WebsocketService
ws:WebSocket;
url="ws://127.0.0.1:25555";
lockReconnect:boolean;
constructor() { }
createObservableSocket(){
let that=this;
this.ws=new WebSocket(this.url);
this.ws.onopen=()=>{
console.log("连接打开");
this.sendMessages("hello");
};
this.ws.onmessage=(event)=> {
};
this.ws.onerror=(event)=>{
that.reConnect();
};
this.ws.onclose=(event)=>{
console.log("连接断开");
that.reConnect();
};
}
reConnect(){
let that=this;
console.log("断线重连");
if (this.lockReconnect) return;
this.lockReconnect = true;
setTimeout(()=>{
this.lockReconnect = false;
},1000);
}
sendMessages(messages:any){
if (this.ws){
if (this.ws.readyState === 1){
this.ws.send(messages);
}else {
console.log(this.ws.readyState);
}
}else {
alert("连接不成功,等待重连!");
setTimeout(()=>{
this.ws.send(messages);
},1000);
}
}
第二种websocket,使用订阅,目前没有断线重连的功能
1.创建一个WebsocketService
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root',
})
export class WebsocketService {
constructor() { }
ws:WebSocket;
//创建可观测的流,包括服务器返回来的消息
createObservableSocket(url:string):Observable<any>{
this.ws=new WebSocket(url);
return new Observable(
observable=>{
//成功返回数据
this.ws.onmessage=(event)=>{observable.next(event.data);};
//返回数据失败,抛出异常
this.ws.onerror=(event)=>{observable.error(event);};
//关闭连接
this.ws.onclose=(event)=>{observable.complete();};
},
);
}
sendMessage(message:any){
let that=this;
if (this.ws){
if (this.ws.readyState === 1){
this.ws.send(JSON.stringify(message));
} else {
console.log(this.ws.readyState);
}
} else {
// socket可能还没连接成功,那么延迟一秒再发送消息
console.log("连接不成功,等待重连");
setTimeout(()=>{
that.ws.send(JSON.stringify(message));
},1000);
}
}
}