gpt4 book ai didi

javascript - 将 javascript 客户端连接到 python websocket 服务器

转载 作者:行者123 更新时间:2023-11-28 22:21:04 25 4
gpt4 key购买 nike

我有这个工作的 python websocket 服务器:

#!/usr/bin/env python
from socket import *

HOST = ''
PORT = 8080
BUFSIZ = 1024
ADDR = (HOST, PORT)

tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

def loop():
while True:
print 'Waiting for connection...'
tcpCliSock, addr = tcpSerSock.accept()
print '...connected from :', addr
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
else:
print 'data: ',data
tcpSerSock.close()

try:
loop()
except KeyboardInterrupt:
tcpSerSock.close()

当我从 python 客户端连接时,即使当我关闭客户端时服务器崩溃,它也能正常工作:

Waiting for connection...
Traceback (most recent call last):
File "ledServer.py", line 27, in <module>
loop()
File "ledServer.py", line 16, in loop
tcpCliSock, addr = tcpSerSock.accept()
File "/usr/lib/python2.7/socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "/usr/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor

无论如何,当我运行这个 javascript 客户端时:

window.onload = function(){
ws = new WebSocket('ws://192.168.25.7:8080');
ws.onmessage = function(event){document.write("message received"); alert(event.data); ws.close();}
ws.onopen = function(){document.write("open");}
ws.onclose = function(){document.write("close");}
ws.onerror = function(){document.write("error");}
}

我在服务器上得到这个:

...connected from : ('192.168.25.25', 53747)
data: GET / HTTP/1.1
Host: 192.168.25.7:8080
Connection: Upgrade
Pragma: no-cache
Cache-Control: no-cache
Upgrade: websocket
Origin: file://
Sec-WebSocket-Version: 13
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36
Accept-Encoding: gzip, deflate
Accept-Language: it-IT,it;q=0.9,en-US;q=0.8,en;q=0.7,tr;q=0.6,nl;q=0.5
Sec-WebSocket-Key: pH4kNOzz1MYyi+oXmaFCcA==
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

但即使服务器说它已连接,在客户端上也不会执行 onopen 函数,Chrome 会说 websocket 状态为“待定”,如果我尝试向服务器发送消息,我会得到:

Uncaught DOMException: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state.

我做错了什么?

最佳答案

Python socket 模块与 websockets 没有任何关系。

与 HTTP 一样,WebSocket 是一种在底层传输之上实现的协议(protocol)。您的代码所做的是设置一个监听端口 8080 的 TCP 服务器。Websockets 是在其之上的一层,就像 HTTP 一样。您可以看到浏览器尝试与您的服务器握手,但它放弃了,因为您的服务器没有适当响应。

websocket 协议(protocol)有些复杂,您可能需要一个库来为您处理它。一个例子是 websockets module :

#!/usr/bin/env python

import asyncio
import websockets

async def echo(websocket, path):
async for message in websocket:
await websocket.send(message)

asyncio.get_event_loop().run_until_complete(
websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()

关于javascript - 将 javascript 客户端连接到 python websocket 服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48553638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com