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?
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.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With