【发布时间】:2021-08-05 01:56:33
【问题描述】:
我正在使用模块 socketserver 创建一个 Python socketserver:
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def setup(self):
pass
def handle(self):
pass
with socketserver.TCPServer(("localhost", 4000), MyTCPHandler) as server:
server.serve_forever()
我使用了 Python 模块 websockets,我可以使用 WebSocket API 在 Javascript 中访问 websocket。在没有完全理解 Python 模块 socketserver 的真正作用的情况下,我尝试使用 websocket 连接到 TCP socketserver:
var socket = new WebSocket('ws://localhost:4000'); // ERROR: Firefox can’t establish a connection to the server at ws://localhost:4000/.
每次,Firefox 都会抛出错误 Firefox can’t establish a connection to the server at ws://localhost:4000/. 然后,我尝试使用 Python http 模块连接到服务器:
import http.client
httpConnection = http.client.HTTPSConnection("localhost:4000", timeout=10)
print(httpConnection) # HTTP Connection Object
很遗憾,这行得通。现在,我了解到 Python 的内置 socketserver 模块创建只能通过 HTTP 访问。现在,我想知道是否可以在浏览器中使用 Javascript 连接到 Python TCP socketserver。如果没有,我将使用websockets 或弄清楚如何创建自己的 websocket。
【问题讨论】:
标签: javascript python http browser websocket