I'm connecting to RSKj using the following endpoint:
ws://localhost:4444/
... However, I am unable to connect.
Note that the equivalent HTTP endpoint http://localhost:4444/
work for me, so I know that my RSKj node is running properly.
I need to listen for newBlockHeaders
, so I prefer to use WebSockets (instead of HTTP).
How can I do this?
WebSockets in Node.js Jun 10, 2019 WebSockets are a tool for bidirectional communication between a browser client and a server. In particular, WebSockets enable the server to push data to the client.
Short answer: No, only the path and protocol field can be specified. There is no method in the JavaScript WebSockets API for specifying additional headers for the client/browser to send. The HTTP path ("GET /xyz") and protocol header ("Sec-WebSocket-Protocol") can be specified in the WebSocket constructor.
The Sec-WebSocket-Protocol header (which is sometimes extended to be used in websocket specific authentication) is generated from the optional second argument to the WebSocket constructor: var ws = new WebSocket ("ws://example.com/path", "protocol"); var ws = new WebSocket ("ws://example.com/path", ["protocol1", "protocol2"]);
We can make use of a single port to spin off the HTTP server and the WebSocket server. The gist below shows the creation of a simple HTTP server. Once it is created, we tie the WebSocket server to the HTTP port:
RSKj by default uses 4444
as the port for the HTTP transport;
and 4445
as the port for the Websockets transport.
Also note that the websockets endpoint is not at /
,
but rather at websocket
.
Therefore use ws://localhost:4445/websocket
as your endpoint.
If you're using web3.js,
you can create a web3
instance that connects over Websockets
using the following:
const Web3 = require('web3');
const wsEndpoint = 'ws://localhost:4445/websocket';
const wsProvider =
new Web3.providers.WebsocketProvider(wsEndpoint);
const web3 = new Web3(wsProvider);
The second part of your question can be done
using eth_subscribe
on newBlockHeaders
.
Using the web3
instance from above like so:
// eth_subscribe newBlockHeaders
web3.eth.subscribe('newBlockHeaders', function(error, blockHeader) {
if (!error) {
// TODO something with blockHeader
} else {
// TODO something with error
}
});
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