In my project I have following websocket handler using tornado websockets:
class EchoWebSocket(tornado.websocket.WebSocketHandler):
def open(self):
print("WebSocket opened")
def on_message(self, message):
self.write_message(u"You said: " + message)
# self.stream_logs()
def on_close(self):
print("WebSocket closed")
I could connect to this websocket from an python client side code given here:
import asyncio
import websockets
async def connect_to_websocket(uri):
async with websockets.connect(uri) as websocket:
await websocket.send("kdkdkd")
while True:
# Receive message from the WebSocket server
message = await websocket.recv()
print(f"Received message: {message}")
async def main():
uri = "ws://localhost:8889/myextension/echows" # WebSocket server URI
await connect_to_websocket(uri)
if __name__ == "__main__":
asyncio.create_task(main())
but when I try to connect it using javascript based client code it throws error VM449:3 WebSocket connection to 'ws://localhost:8889/myextension/echows/' failed javscript client code goes as:
async function connectToWebSocket(uri) {
try {
const connection = await new WebSocket(uri);
connection.onmessage = (event) => {
console.log(`Received message: ${event.data}`);
};
connection.onerror = (error) => {
console.error('WebSocket error:', error);
};
await connection.send("kdkdkd");
while (connection.readyState === WebSocket.OPEN) {
// Receive messages and handle them appropriately (e.g., print or process)
const message = await connection.receive();
console.log(`Received message: ${message}`);
}
} catch (error) {
console.error('Connection error:', error);
}
}
const uri = "ws://localhost:8889/myextension/echows/";
connectToWebSocket(uri);
I cannot figure out what am I doing wrong in js code although everything working while connecting using python.