【问题标题】:how to send a message on a typescript websocket如何在打字稿websocket上发送消息
【发布时间】:2017-04-12 22:57:41
【问题描述】:

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

在角度方面,我有一项服务

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

在模拟服务器端,我有一个打字稿节点服务器,它按如下方式创建套接字:

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发送消息?

【问题讨论】:

    标签: javascript node.js angular websocket


    【解决方案1】:

    我不确定你在问什么。这行是正确的:

    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

    【讨论】:

    • 感谢您的链接中列出了我正在寻找的内容。 websocket.on('message', 就是我要找的东西
    猜你喜欢
    • 2021-08-15
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    相关资源
    最近更新 更多