Tree Service
  • 🌳Welcome
    • How to Subscribe
  • 📈Tree Terminal
    • Installation
    • Setup
      • Create Binance API
      • Create Bybit API
      • Create OKX API
    • First-Timer Checklist
    • Features
      • 📈Charts
      • 📰News feed
      • 📋Command line
      • 💸Positions & orders
      • 💰Accounts
      • 💲Symbols
      • 🤖Botting
      • 📕Orderbook
      • 👆Buttons
      • Customization
      • 🔔Notifications
      • Filters
    • Security
    • FAQ
  • 🗃️Websockets
    • API Key
    • Python connection
    • JavaScript connection
    • Response
    • Like/Dislike feature
    • News history
Powered by GitBook
On this page
  1. Websockets

JavaScript connection

Websocket connection using JS

import React, { useEffect, useState } from 'react';

const WebSocketComponent = () => {
    const [ws, setWs] = useState(null);
    const API_KEY = 'YOUR_API_KEY'; // Replace with your actual API key

    useEffect(() => {
        // Create WebSocket connection.
        const webSocket = new WebSocket('wss://news.treeofalpha.com/ws');

        // Connection opened
        webSocket.onopen = (event) => {
            console.log('Connection opened');
            webSocket.send(`login ${API_KEY}`);
        };

        // Listen for messages
        webSocket.onmessage = (event) => {
            console.log('Message from server ', event.data);
        };

        // Listen for possible errors
        webSocket.onerror = (error) => {
            console.error('WebSocket error: ', error);
        };

        // Listen for the close event
        webSocket.onclose = (event) => {
            console.log('WebSocket is closed now.');
        };

        // Assign the WebSocket object to state
        setWs(webSocket);

        // Perform cleanup
        return () => {
            webSocket.close();
        };
    }, []); // The empty array causes this effect to only run on mount

    return (
        <div>
            <h1>WebSocket Example</h1>
            {/* You can add more UI elements here that interact with WebSocket */}
        </div>
    );
};

export default WebSocketComponent;
PreviousPython connectionNextResponse

Last updated 5 months ago

🗃️