gpt4 book ai didi

typescript - 如何在 typescript 上重新连接(重新订阅)到 websocket

转载 作者:搜寻专家 更新时间:2023-10-30 21:47:55 24 4
gpt4 key购买 nike

我有一个 Ionic3 应用程序,在某个 View 上,在 View 输入时连接并订阅 websocket 可观察/观察者服务:

subscribtion: Subscription;


ionViewDidEnter() {
this.subscribtion = this.socket.message.subscribe(msg => {
let configs = <Configs>msg.data
this.inputs = configs.inputs;
});
this.socket.message.next(this.enterMessage);
}

然后,在离开 View 时,取消订阅:

ionViewWillLeave() {
this.socket.message.next(this.quitMessage);
this.subscribtion.unsubscribe();
}

但是如果我重新进入 View ,它不会重新连接到 websocket。我应该怎么做?

这里是套接字和 websocket.ts :

@Injectable()
export class SocketProvider {

public message: Subject<Message>;

constructor(private socket: WebsocketProvider, @Inject('server') private server) {
console.log('Hello SocketProvider Provider');
let wsAddr = this.server.webSocketUrl();
this.message = <Subject<Message>>socket
.connect(wsAddr)
.map((response: MessageEvent): Message => {
let data = JSON.parse(response.data);
return data;
})
}

}


private subject: Rx.Subject<MessageEvent>;

public connect(url): Rx.Subject<MessageEvent> {
if (!this.subject) {
this.subject = this.create(url);
//console.log('successfully Connnect: ' + url);
}
return this.subject;
}

public create(url): Rx.Subject<MessageEvent> {
let ws = new WebSocket(url);

let observable = Rx.Observable.create(
(obs: Rx.Observer<MessageEvent>) => {
ws.onmessage = obs.next.bind(obs);
ws.onerror = obs.error.bind(obs);
ws.onclose = obs.complete.bind(obs);
return ws.close.bind(ws);
}
)

let observer = {
next: (data: Object) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(data));
}
}
}

return Rx.Subject.create(observer, observable);
}
}

最佳答案

我找到了一个解决方案:

我将 socket.ts 中构造函数中的代码移动到我在 IonViewEnter() 中调用的连接函数中并重新初始化 WebSocketProvider 对象:

constructor(private socket: WebsocketProvider, @Inject('server') private server) {
console.log('Hello SocketProvider Provider');
}

connect() {
console.log("try to connect eb socket");
this.socket = new WebsocketProvider;
let wsAddr = this.server.webSocketUrl();
//let wsAddr = 'ws://192.168.0.110:8181';
this.message = <Subject<Message>>this.socket
//.connect('wss://echo.websocket.org')
.connect(wsAddr)
.map((response: MessageEvent): Message => {
try {
let data = JSON.parse(response.data);
return data;
}catch(e) {
alert(e);
console.log("receive invalid JSON message: ");
console.log(response.data);
}
})
}

关于typescript - 如何在 typescript 上重新连接(重新订阅)到 websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51458349/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com