Ionic WebSocket 使用
编写写一个工具类
import { Injectable } from '@angular/core';
import { Observable } from "rxjs/Observable";
import {observable} from "rxjs/symbol/observable";
@Injectable()
export class WebSocketService {
ws:WebSocket
constructor(){
}
createObservableSocket(url:string ):Observable<any>{
this.ws = new WebSocket(url);
return new Observable<any>(
observable =>{
this.ws.onmessage = (event)=> observable.next(event.data);
this.ws.onerror = (event)=>observable.error(event);
this.ws.onclose = (event)=>observable.complete();
}
)
}
sendMessage(message:string){
this.ws.send(message);
}
}
当然 rxjs 需要自己安装一下
npm install rxjs
如果是高版本的话可能会说找不到,需要改一下导入的包:
import { Observable} from 'rxjs';
import {observable} from 'rxjs';
改完之后就没问题了应该。
组件中引用
import {WebSocketService} from "../service/websocket.service";
Component里配置
@Component({
selector: 'app-home',
templateUrl: 'home.page.html',
styleUrls: ['home.page.scss'],
providers: [WebSocketService]
})
构造函数里声明
constructor( private wsService:WebSocketService) {}
使用
连接接受消息
init(){
this.wsService.createObservableSocket('ws://121.40.165.18:8800').subscribe(rep =>{
console.log(rep)
},error=>{
console.log("出错")
});
console.log('已连接 ws://121.40.165.18:8800')
}
发送消息
sendMessage(){
this.wsService.sendMessage("123")
}