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;
Last updated