Geth Websockets: Connectivity and Examples

Follow
  •  

 

 Summary

With websockets enabled a user is able to create a connection to their node in order to create subscriptions. This allows the user to wait for events instead of polling for the data on their node. For every event that matches the subscription a JSON-RPC notification with details will be sent to the client. This only works for current/future events, websocket subscriptions should not be used for past events. Subscriptions are related to the connection, if the connection is closed all subscriptions will be removed.

 

Supported Subscriptions

Below you will find the list of supported subscriptions on geth:

  • newHeads
  • logs
  • newPendingTransactions
  • Syncing 

 

How to create a websocket connection

You will need to use a websocket client to create connections to your node. In the examples below we will be using wscat to connect to our nodes. You will also need to use a specific port and endpoint to connect to your node while using your node auth token. Below you will see an example on how to connect to a node:

W3socket endpoint - in your dashboard

geth_websocket_endpoint.jpg

wscat -H 'X-Auth-Token: <AUTH_TOKEN> -c wss://<NODE_ID>.bdnodes.net:8443/websocket Connected (press CTRL+C to quit)

 

  • Important Note: If your connection is idle for more than 60 seconds it will be automatically closed. A connection is considered idle if the client does not send any request to the node. Even if your subscription is streaming data, the client needs to make a request to the node or else the connection is closed automatically.

    Call RPC endpoints with websocket

    You can also use regular RPC endpoints with a websocket connection. After connecting you will see a prompt where you call RPC endpoints. Below you will find some examples:


    Check the syncing status of the node

    > {"jsonrpc":"2.0","method":"eth_syncing","params":[],"id":1}
    < {"jsonrpc":"2.0","result":{"currentBlock":"0x0","highestBlock":"0xb2f739","startingBlock":"0x0","warpChunksAmount":"0x13f8","warpChunksProcessed":"0x6e0"},"id":1}

    Check the number of peers on the node 

    > {"id":1,"jsonrpc":"2.0""method":"net_peerCount","params":[]}
    < {"jsonrpc":"2.0","result":"0x27","id":1}

    You can call any of our RPC endpoints with a websocket connection. <insert link to KB article with whitelist>


    Create a subscription

    With a websocket connection you can create any number of subscriptions to the supported list. Each subscription will have a unique ID to identify them which allows you to have multiple subscriptions to the same supported subscriptions type. In order for websocket to stream data correctly the node needs to be fully synced, since the data being streamed is new on the network. This will not work if your node is still syncing.


    We will create a subscription so the newHeads event, you will see that is contains a unique ID and will return data when it becomes available:

    >{"id": 1,"jsonrpc":"2.0","method": "eth_subscribe","params": ["newHeads"]} {"jsonrpc":"2.0","id":1,"result":"0x37de8e6f5498f596a17cdfd72b53fffc"}{"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x37de8e6f5498f596a17cdfd72b53fffc","result":{"parentHash":"0x8098360ff8e217b96ee422fab26cd7bcc2546f3bd726e204a0150e726c1977d4","sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","miner":"0xea674fdde714fd979de3edf0f56aa9716b898ec8","stateRoot":"0xd8917c2953fcbe25f9519589892fc534b857ab29a8c8ce3f2dce8279db166f68","transactionsRoot":"0x59abe735e8f26d5465e5beba6e7a27c6015952fe8b1da8811571c3dcc684bba4","receiptsRoot":"0x59019f2fa636fa4625d0aa2ab0c8a4ff1864ebe61a08e2aebfa4cab16080d226","logsBloom":"0x1aa2c12d54868c1091c0851498453b2488c6831422802c84e02190c01242130b4e0441640080061056827042105083712220980c6b348a0012109884802682005d40605ca700c262f883014c310408e71722d70ea04840241d066c76c8c240019e0088871646840421ca04158812a8d20040222f60ca8e0442910934c06acd4068009413086c46b400e00540908ed8030054200b1152f048e120a950265e2562861404040e1068628050c390313584410000004d8536182054424d621020c1749050464a6884b9402828020108eb00040e4602040647ca1c043a586e24e0302c01fce4f0240bf42324005c0400208097657c880200c90467e01642c80e2612a3","difficulty":"0xf168052311d0d","number":"0xb289a9","gasLimit":"0xbe5a91","gasUsed":"0xbe3d2b","timestamp":"0x6009d2e3","extraData":"0x65746865726d696e652d7573312d322d67657468","mixHash":"0x86ee1b009df30c523b3af763742e3db197de58f37cdbdba62303390a3538c710","nonce":"0x4d2b99e60d83ce1e","hash":"0xf3c191c5e0baad183dc38b70ee9da2e4cf581759dd3af41974840e4ed7b33ea7"}}}

    Unsubscribe from a subscription

    Subscriptions are running as long as the connection is opened and receiving data. If you wish to remove a specific subscription you will need to provide the ID when removing it. If no valid ID is passed the subscription will not be removed. We will unsubscribe from the above subscription in our example:


    > {"id"<: 1,"jsonrpc":"2.0","method""eth_unsubscribe","params": ["0x37de8e6f5498f596a17cdfd72b53fffc"]}
    < {"jsonrpc":"2.0","id":1,"result":true}

    Simple Websocket Script

    Above we have shown you independent examples of how websocket works. Below you will find a simple script using Web3.js with subscriptions and websocket connections. The script is making a subscription to newPendingTransactions, then taking the hash for each new transaction and getting the transaction information using an RPC endpoint. This script will stream all the details of each new transaction in the network.

    var Web3 = require('web3');

    subscription = web3.eth.subscribe('pendingTransactions', function (error, result) {})
        .on("data", function (transactionHash) {
            web3.eth.getTransaction(transactionHash)
            .then(function (transaction) {
              console.log(transaction)
            });
        })

     

    Additional Links

    Above you saw a brief explanation of websockets and how to use them. Below you can find additional information regarding websocket connections and their subscriptions.

    Official documentation to Web3.js
0 out of 0 found this helpful

Comments

0 comments

Please sign in to leave a comment.