I have a small "server" applet in Python that launches an application and starts a server waiting for some data via websocket:
#!python3
import os
import subprocess
import asyncio
import websockets
async def hello(websocket, path):
name = await websocket.recv()
print("< {}".format(name))
greeting = "Hello {}!".format(name)
await websocket.send(greeting)
print("> {}".format(greeting))
subprocess.Popen(['C:\\...\\some_app.exe', 'd:\\data\\app_data.txt'])
start_server = websockets.serve(hello, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
The application has a plugin that uses Javascript websockets to connect to the server. In the global part of the js file, I establish a connection:
const socket = new WebSocket('ws://localhost:8765');
//
socket.addEventListener('open', function (event) {
socket.send('Connection Established');
});
socket.addEventListener('message', function (event) {
console.log(event.data);
});
The connection does get established when this code runs, however, in another function, when I try to send data, it fails:
alert("Gonna use socket!");
if (socket.readyState == 1) {
socket.send('foo');
socket.close();
} else {
alert("Socket not ready!");
}
Why does the socket get closed? Is there any way to keep it open (or is that bad practice)?