Using Websockets with Web3

Project Source Code

Get the project source code below, and follow along with the lesson material.

Download Project Source Code

To set up the project on your local machine, please follow the directions provided in the README.md file. If you run into any issues with running the project source code, then feel free to reach out to the author in the course's Discord channel.

This lesson preview is part of the Million Ether Homepage course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

This video is available to students only
Unlock This Course

Get unlimited access to Million Ether Homepage, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Million Ether Homepage

Web3 can connect to our Ethereum node using WebSockets. WebSockets will let us keep a two-way connection open between our browser and our client. This means that our Geth node will be able to push real-time updates to our browser. We'll use this on our page to instantly draw any pixels that are purchased. In order to use WebSockets with Geth, we need to add some parameters to our G eth command. They look like the flags we used for RPC only they begin with WS for WebSockets . Here's the command which you can copy and paste from the video notes. Now in our index.js, let's connect to Geth using the Web3 WebSocket provider. We'll write a function "check balance". Let's check our account balances just to make sure the connection works. And let's add this "check balance" function to our document on load. If we take a look at our browser console, we can see that the account balance is there, so it worked. If you didn't see those balances, double check that your Geth is running and that the hostname and port match.