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