I am trying to make a connection from my javascript client in a browser to my python server and to send data from the server to the client, but when trying to connect I get the error: failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
I tried using wss instead of ws.
I also tried using socket.io instead of websocket, which wasn't helping either. I don't remember all the things I tried but none of them helped.
Javascript client:
var conn = new WebSocket('ws://localhost:2001');
conn.onmessage = function (event) {
console.log(event.data);
Python server:
# Echo server program
import socket
HOST = 'localhost'
PORT = 2001
def sendSensorData(data):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(HOST, PORT)
s.listen(1)
conn, addr = s.accept()
with conn:
print('Connected by', addr)
while True:
print(data)
message = str(data).encode()
try:
# if not data: break
conn.sendall(message)
except BaseException as e:
print (e)
Edit: This is the error from python:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/Users/joep/Documents/GitHub/Walnut-installation-web-app/testAPI/workers/sensorStream.py", line 26, in sensorStream
sendSensorData.sendSensorData(data)
File "/Users/joep/Documents/GitHub/Walnut-installation-web-app/testAPI/functions/sendSensorData.py", line 19, in sendSensorData
conn.send(message)
BrokenPipeError: [Errno 32] Broken pipe
Hopefully it is a simple trick to fix it.
socket.bind()no longer accepts a pair of parameters, only a tuple;s.bind((HOST, PORT))s.bind():) Also, note that there is a dedicated WebSockets package available for Python that wraps a high-level API around the low-level socket interface, implements the websockets protocol and provides asyncio-based concurrency out of the box.