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

时间:2018-09-16 21:47:40

标签: javascript python sockets websocket

我正在尝试在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遇到的错误与我的不一样。

1 个答案:

答案 0 :(得分:2)

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