WebSocket python服务器和JS客户端的握手错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebSocket python服务器和JS客户端的握手错误相关的知识,希望对你有一定的参考价值。

我试图建立一个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
') #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遇到的错误与我的不一样。

答案

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

以上是关于WebSocket python服务器和JS客户端的握手错误的主要内容,如果未能解决你的问题,请参考以下文章

Node.js实现WebSocket客户端

如何使用WebSocket

受祝福的服务器(Node.js)通过 websocket 到浏览器中的 Xterm.js 客户端

Websocket 服务器和移动客户端

Node.js网络编程--WebSocket协议

python怎么连接websocket