Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Websocket Subscribe to Channel

I am trying to subscribe to channel using native WebSocket in vanilla javascript (without using any library) [as I have just read it's possible but I am not sure - please correct me if I'm wrong].

I am trying to get the latest price of bitcoin

let ws = new WebSocket('wss://ws-feed.gdax.com');

var params = {
   "type": "subscribe",
   "channels": [{"name": "ticker", "product_ids": ["BTC-USD"]}]
}

ws.onmessage = function(msg) {
    console.log(msg);
}

I am trying to connect to this channel, however I couldn't manage to do it. I am not getting any outputs in the console.

How do I give the parameters into the channel and start listening to it?

like image 923
senty Avatar asked Mar 25 '18 08:03

senty


People also ask

What is WebSocket subscription?

The WebSocket subscriber receives notifications from topics and publishes them over TCP to WebSocket-supported clients that are connected to the FME Server WebSocket Server or another target URL.

What is the difference between WS and WSS?

The wss protocol establishes a WebSocket over an encrypted TLS connection, while the ws protocol uses an unencrypted connection. At this point, the network connection remains open and can be used to send WebSocket messages in either direction.

How do I call a Javascript WebSocket?

To open a websocket connection, we need to create new WebSocket using the special protocol ws in the url: let socket = new WebSocket("ws://javascript.info"); There's also encrypted wss:// protocol. It's like HTTPS for websockets.

How do Javascript WebSockets work?

The WebSocket API is an advanced technology that makes it possible to open a two-way interactive communication session between the user's browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply.


1 Answers

Below is an example on how to subscribe to 'ArticlesChannel' using vanilla html5 websockets.

let ws = new WebSocket('ws://localhost:4000/cable');

ws.onopen = function(){
  //Subscribe to the channel
  ws.send(JSON.stringify({"command": "subscribe","identifier":"{\"channel\":\"ArticlesChannel\"}"}))
}    

ws.onmessage = function(msg) {
    console.log(JSON.parse(msg.data).message);
}
like image 104
Dinesh Avatar answered Oct 27 '22 17:10

Dinesh