【问题标题】:Handshake error with WebSocket python server and JS clientWebSocket python服务器和JS客户端的握手错误
【发布时间】:2019-02-20 20:15:27
【问题描述】:

我正在尝试在 python 脚本(它将对无法在 javascript 中完成的数据进行大量计算并将该数据作为 json 发送)和 javascript 客户端之间建立通信。

我的 python 服务器有以下代码:

import socket
import sys
from thread import *

HOST = ''   # Symbolic name meaning all available interfaces
PORT = 9888 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn):
    #Sending message to connected client
    conn.send('Welcome to the server. Type something and hit enter\n') #send only takes string

    #infinite loop so that function do not terminate and thread do not end.
    while True:

        #Receiving from client
        data = conn.recv(1024)
        reply = 'OK...' + data
        if not data: 
            break

        conn.sendall(reply)

    #came out of loop
    conn.close()

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,))

s.close()

我的 javascript 客户端的以下代码:

var connection = new WebSocket('ws://127.0.0.1:8999');
connection.onopen = function () {
  connection.send('Hello'); // Send the message to the server
};

我从我的 javascript 客户端收到以下错误:

Error during WebSocket handshake: net::ERR_INVALID_HTTP_RESPONSE

我的 python 服务器的以下输出

Socket created
Socket bind complete
Socket now listening
Connected with 127.0.0.1:53956
Unhandled exception in thread started by <function clientthread at 0x10abac578>
Traceback (most recent call last):
  File "server.py", line 71, in clientthread
    data = conn.recv(1024)
socket.error: [Errno 54] Connection reset by peer

有谁知道出了什么问题?

编辑:忘了说我之前看过这个SO Post,但是我的问题不一样,或者应该说OP遇到的错误和我的不一样。

【问题讨论】:

    标签: javascript python sockets websocket


    【解决方案1】:

    WebSocket 与您创建的普通 TCP 套接字不同。 WebSocket 是基于 TCP 的协议,它以 HTTP 握手开始,然后继续使用基于帧的协议。如果您想在 Python 中实现 WebSocket 服务器,您需要按照RFC 6455 中指定的方式实现此协议或使用existing WebSocket libraries

    使用 WebSocket 的示例服务器端 python 代码是:

    import asyncio
    import websockets
    
    async def handle_message(message):
        print(message)
    
    async def consumer_handler(websocket, path):
        while True:
            message = await websocket.recv()
            await handle_message(message)
    
    start_server = websockets.serve(consumer_handler, 'localhost', 8765)
    
    asyncio.get_event_loop().run_until_complete(start_server)
    asyncio.get_event_loop().run_forever()
    

    【讨论】:

    • 感谢您的指点。我接受了您的回答并在此处添加了示例代码以使其更完整。
    猜你喜欢
    • 2011-12-26
    • 2012-11-11
    • 2018-09-10
    • 1970-01-01
    • 2018-08-23
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多