# Connect via Web Socket

{% hint style="info" %}
**Good to know:** All mempool data are sent as a JSON payload, you must use the following ws address with your API Key appended to connect:

wss\://api.mempoolnode.com/ws?apiKey={YOUR-API-KEY}<br>

\*Where "{YOUR-API-KEY}" is to be replaced with your API Key.

{% endhint %}

## Getting Started

### Setup API Configuration

1. Create a Mempool Node account, by clicking the "Register" button on the top right of our [Dashboard](https://dashboard.mempoolnode.com/?ref=apiDocs), and complete the registration form. &#x20;
2. Mempool Node will create an API Key named "Mempool Key 1" for your account, that you can configure to use. You can create additional API keys from your [Dashboard](https://dashboard.mempoolnode.com/?ref=apiDocs) by clicking the "+" button at the top right of Mempool Key 1.

<figure><img src="https://741570820-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmCVQlrfKJPNWY2fRf5qN%2Fuploads%2FSQid8tY6fJyvJ8NIxtzw%2FAdd%20Mempool%20Key.png?alt=media&#x26;token=6f050e5c-4d8f-4713-9a9d-d49d6daf7c0f" alt="" width="75"><figcaption><p>Add API Configuration Key</p></figcaption></figure>

### Configure Web Socket

Configure a new web socket for your API configuration by toggling the "Webhook/Web Socket" to "Web Socket" and then clicking "⋮" next to the On/Off toggle on the right, and selecting "Configure". This will open a form, in which you populate your webhook specifics: Whitelist Addresses, Blockchain(Currently Ethereum & Binance Smart Chain are supported) & Watched Addresses. Once completed, click the green "Save" button.

<figure><img src="https://741570820-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmCVQlrfKJPNWY2fRf5qN%2Fuploads%2FIjXgd04FHulTc0N2H9ax%2FSet%20Up%20Web%20Socket.png?alt=media&#x26;token=93e0dc24-6c5f-473d-ab96-ca76cad0aea6" alt=""><figcaption><p>Web Socket Configuration Form for API Mempool Key</p></figcaption></figure>

### Add Whitelist Addresses

By default there is a field available for you to enter a valid IP or URL address to whitelist, however, to add an additional address to whitelist click the "+" on the right of "Whitelist Addresses" and enter the address you wish to whitelist. Once completed, click the green "Save" button.

### Add Address to Watch

By default there is a field available for you to enter an address to watch, however, to add an additional address to watch click the "+" on the right of "Watched Addresses" and enter the address you wish to watch. Once completed, click the green "Save" button.

{% hint style="info" %}
Ethereum & Binance Smart Chain addresses start with "0x" followed by 40 characters. Any valid ETH or BSC address will be accepted, this also includes external accounts and smart contract addresses.
{% endhint %}

To stop watching a specific address entered, you can click the trash/bin icon next to the address, and once saved, you'll no longer watch that address. Once completed, click the green "Save" button.

### Start Receiving Data via Web Socket

Now that everything is configured, all you have to do is toggle the On/Off switch for the specific Mempool API Key you wish to start receiving data, and your mempool data will begin to fly in. Viola!

<figure><img src="https://741570820-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmCVQlrfKJPNWY2fRf5qN%2Fuploads%2FeOoo9zoYVF6IOAjpGuNn%2FToggle%20On%20Web%20Socket.png?alt=media&#x26;token=a1076989-1399-4ccf-ad97-e6cad7ea4d26" alt=""><figcaption><p>Toggle On Web Socket</p></figcaption></figure>

## Examples in Javascript, Rust, TypeScript, Java, , C++, Python & C\#

{% tabs %}
{% tab title="Javascript" %}

```javascript
const WebSocket = require('websocket').client;

const apiKey = "YOUR-API-KEY"; // Replace with your actual API key
const wsUrl = `wss://api.mempoolnode.com/ws?apiKey=${apiKey}`;

const client = new WebSocket();

client.on('connectFailed', (error) => {
    console.error(`Connection error: ${error.toString()}`);
});

client.on('connect', (connection) => {
    console.log('Connected to WebSocket');

    connection.on('error', (error) => {
        console.error(`Connection error: ${error.toString()}`);
    });

    connection.on('close', () => {
        console.log('Connection closed');
    });

    connection.on('message', (message) => {
        if (message.type === 'utf8') {
            console.log(`Received data: ${message.utf8Data}`);
        }
    });
});

client.connect(wsUrl);

```

{% endtab %}

{% tab title="TypeScript" %}

```
import * as WebSocket from 'websocket';

const apiKey = "YOUR-API-KEY"; // Replace with your actual API key
const wsUrl = `wss://api.mempoolnode.com/ws?apiKey=${apiKey}`;

const client = new WebSocket.client();

client.on('connect', (connection) => {
    console.log('Connected to WebSocket');

    connection.on('message', (message) => {
        if (message.type === 'utf8') {
            console.log(`Received data: ${message.utf8Data}`);
        }
    });

    connection.on('close', () => {
        console.log('WebSocket connection closed');
    });
});

client.connect(wsUrl);

```

{% endtab %}

{% tab title="Rust" %}

```
use async_tungstenite::tungstenite::protocol::Message;
use futures_util::stream::StreamExt;
use std::error::Error;
use async_tungstenite::tokio::connect_async;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let api_key = "YOUR-API-KEY"; // Replace with your actual API key
    let ws_url = format!("wss://api.mempoolnode.com/ws?apiKey={}", api_key);

    let (ws_stream, _) = connect_async(ws_url).await?;
    let (mut write_stream, mut read_stream) = ws_stream.split();

    while let Some(Ok(msg)) = read_stream.next().await {
        if let Message::Text(data) = msg {
            println!("Received data: {}", data);
        }
    }

    Ok(())
}

```

{% endtab %}

{% tab title="Java" %}

```
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;

public class WebSocketExample {
    public static void main(String[] args) throws URISyntaxException {
        String apiKey = "YOUR-API-KEY"; // Replace with your actual API key
        String wsUrl = "wss://api.mempoolnode.com/ws?apiKey=" + apiKey;

        WebSocketClient client = new WebSocketClient(new URI(wsUrl)) {
            @Override
            public void onOpen(ServerHandshake serverHandshake) {
                System.out.println("Connected to WebSocket");
            }

            @Override
            public void onMessage(String message) {
                System.out.println("Received data: " + message);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                System.out.println("WebSocket connection closed");
            }

            @Override
            public void onError(Exception e) {
                e.printStackTrace();
            }
        };

        client.connect();
    }
}

```

{% endtab %}

{% tab title="Python" %}

```python
import asyncio
import websockets

async def connect_to_websocket():
    api_key = "YOUR-API-KEY"  # Replace with your actual API key
    ws_url = f"wss://api.mempoolnode.com/ws?apiKey={api_key}"

    async with websockets.connect(ws_url) as websocket:
        while True:
            # Receive and process data from the WebSocket server as needed
            data = await websocket.recv()
            print(f"Received data: {data}")

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(connect_to_websocket())TypeScript
```

{% endtab %}

{% tab title="C#" %}

```csharp
using System;
using WebSocketSharp;

class Program
{
    static void Main(string[] args)
    {
        string apiKey = "YOUR-API-KEY"; // Replace with your actual API key
        string wsUrl = $"wss://api.mempoolnode.com/ws?apiKey={apiKey}";

        using (var ws = new WebSocket(wsUrl))
        {
            ws.OnMessage += (sender, e) =>
            {
                if (e.IsText)
                {
                    Console.WriteLine($"Received data: {e.Data}");
                }
            };

            ws.OnError += (sender, e) =>
            {
                Console.WriteLine($"WebSocket error: {e.Message}");
            };

            ws.OnClose += (sender, e) =>
            {
                Console.WriteLine("WebSocket connection closed");
            };

            ws.Connect();
            Console.WriteLine("Connected to WebSocket");

            Console.ReadLine(); // Keep the application running
        }
    }
}

```

{% endtab %}

{% tab title="C++" %}

```
#include <iostream>
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/client.hpp>

typedef websocketpp::client<websocketpp::config::asio_tls_client> client;

int main() {
    std::string apiKey = "YOUR-API-KEY"; // Replace with your actual API key
    std::string wsUrl = "wss://api.mempoolnode.com/ws?apiKey=" + apiKey;

    client c;

    c.init_asio();

    c.set_tls_init_handler([](websocketpp::connection_hdl) {
        return websocketpp::lib::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::tlsv12);
    });

    c.set_message_handler([](websocketpp::connection_hdl hdl, client::message_ptr msg) {
        if (msg->get_opcode() == websocketpp::frame::opcode::text) {
            std::cout << "Received data: " << msg->get_payload() << std::endl;
        }
    });

    websocketpp::lib::error_code ec;
    client::connection_ptr con = c.get_connection(wsUrl, ec);

    if (ec) {
        std::cout << "Error connecting: " << ec.message() << std::endl;
        return 1;
    }

    c.connect(con);

    c.run();

    return 0;
}

```

{% endtab %}
{% endtabs %}
