reza
reza

Reputation: 6358

how to send a message on a typescript websocket

I have an angular application needing to subscribe to a websocket for incoming data.

On the angular side, in a service I have

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

and on the mock server side, I have a typescript node server that creates the socket as follows:

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'));//////

my question is how to use the wsServer to send messages?

Upvotes: 1

Views: 7128

Answers (1)

Yakov Fain
Yakov Fain

Reputation: 12376

I'm not sure what are you asking about. This line is correct:

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

If you want to keep sending messages to all connected clients, you need to either use the property wsServer.clients to send messages to each connected client, or store the references to each connected client (the websocket variable in your code) in an array and then send the messages to each client using forEach().

Take a look at this code sample: https://github.com/Farata/angular2typescript/blob/master/chapter8/http_websocket_samples/server/bids/bid-server.ts

Upvotes: 1

Related Questions