Ionic - WebSocket在Ionic里的使用

陆雅志
2023-12-01

因为需要使用WebSocket做TCP的长连接,网上搜了socket.io没找到合适的解决方案。就用原生的了。

 

贴代码:

先写一个工具类

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);
  }
}

把基本的方法封装成工具类,给某个组件调用

 

在组件中

import {WebSocketService} from "../../../../kit/WebSocketService";

Component里配置 

@Component({
  selector: 'xxx',
  templateUrl: 'xxx.html',
  providers: [WebSocketService]
})

构造函数里声明

constructor(private wsService:WebSocketService)

生命周期中调用连接方法

ionViewDidLoad() {
    console.log('ionViewDidLoad');
    //WS连接的IP和端口提前保存在localStorage里,现在读出来
    const printsIp = localStorage.getItem("prints-ipAddress");
    const printsPort = localStorage.getItem("prints-port");
    console.log(printsIp)
    console.log(printsPort)
    if(printsIp != null && printsPort !=null){
      this.wsService.createObservableSocket(`ws://${printsIp}:${printsPort}`);
      console.log(`已连接ws://${printsIp}:${printsPort}`)
    }else {
      console.log("请配置打印机");
    }
  }

 

ws.send方法就不用说了吧

 

 

 类似资料: