gpt4 book ai didi

javascript - 如何在 TypeScript WebSocket 上发送消息

转载 作者:行者123 更新时间:2023-12-03 04:33:48 26 4
gpt4 key购买 nike

我有一个 Angular 应用程序需要订阅 Websocket 以获取传入数据。

从 Angular 来看,在我提供的服务中

setContextChannel(channel) {
this.contextWS = new WebSocket(channel);
that = this;
this.contextWS.onmessage = function(event) {
console.log('ws', event.data);
that.patientID = event.data;
};

this.contextWS.onerror = function(event) {
console.log('ws error', event);
}
}

在模拟服务器端,我有一个 typescript Node 服务器,它创建套接字,如下所示:

import {Server} from "ws";
var wsServer: Server = new Server({port: 8085});
console.log('ws on 8085');
wsServer.on('connection',websocket => websocket.send('first pushed message'));//////

我的问题是如何使用wsServer发送消息?

最佳答案

不知道你想问什么。这行是正确的:

wsServer.on('connection',websocket => websocket.send('first pushed message'));

如果您想继续向所有连接的客户端发送消息,则需要使用属性 wsServer.clients 向每个连接的客户端发送消息,或者存储对每个连接的客户端的引用(websocket 代码中的变量)放入数组中,然后使用 forEach() 将消息发送到每个客户端。

看看这个代码示例:https://github.com/Farata/angular2typescript/blob/master/chapter8/http_websocket_samples/server/bids/bid-server.ts

关于javascript - 如何在 TypeScript WebSocket 上发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43380925/

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