尝试使用websocket javascript客户端连接到python套接字时出错

时间:2019-04-26 07:31:49

标签: javascript python sockets websocket

我正在尝试从浏览器中的javascript客户端连接到python服务器,并将数据从服务器发送到客户端,但是尝试连接时出现错误:failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

我尝试使用wss代替ws。 我还尝试使用socket.io而不是websocket,但这都没有帮助。我不记得我尝试过的所有事情,但都无济于事。

JavaScript客户端:

var conn = new WebSocket('ws://localhost:2001');
    conn.onmessage = function (event) {
     console.log(event.data);

Python服务器:

# 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)

编辑:这是来自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

希望这是修复它的简单技巧。

0 个答案:

没有答案