有没有Python websocket库公开*socket*功能?

2024-05-29 06:57:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我要做一个基于web的实时游戏,需要使用websockets(请不要在这里指Flash),所以我需要一个支持websockets的后端服务器。我决定使用Python有很多原因,但是我很难找到合适的库。具体地说,它必须在常规套接字之上实现websockets,而不是像不透明的黑盒。因为实际上,websocket只不过是传统的套接字,除了非常特殊的握手。在

我研究了许多支持Python websocket的库,但它们似乎都没有公开实际的socket功能,也许我遗漏了一些东西,但我什么也找不到。它们似乎都实现了这样一种模式:定义套接字解析器的行为(它们是整个应用程序的基石),然后启动库的主循环。这是不合适的,因为1)网络环路不是这里的主环路,2)套接字只用于来回传输数据。在

那么,有没有这样的库可以让我使用websockets,比如常规的sockets,而不是抽象的webserver数据端口,还是我真的更好地从现有的库中剥离出有问题的功能,然后像往常一样继续?在


Tags: 功能服务器web游戏websockets模式黑盒原因
2条回答

你的要求毫无意义。在

您认为,在初始握手之后,websocket只是TCP套接字。在

但他们不是。websocket是消息流,而不是字节流。正如Protocol Overview所解释的:

After a successful handshake, clients and servers transfer data back and forth in conceptual units referred to in this specification as "messages". On the wire, a message is composed of one or more frames. The WebSocket message does not necessarily correspond to a particular network layer framing, as a fragmented message may be coalesced or split by an intermediary.

A frame has an associated type. Each frame belonging to the same message contains the same type of data. Broadly speaking, there are types for textual data (which is interpreted as UTF-8 RFC3629 text), binary data (whose interpretation is left up to the application), and control frames (which are not intended to carry data for the application but instead for protocol-level signaling, such as to signal that the connection should be closed). This version of the protocol defines six frame types and leaves ten reserved for future use.

请参见Design Philosophy以了解它的工作方式,并查看Data Framing以了解更完整的详细信息。在

因此,如果您只是从websocket下面取出TCP套接字并开始发送未加帧的数据,另一方将无法理解您,而只会断开连接。在

(您也会破坏大多数代理,因为代理支持依赖于帧屏蔽(如果您不使用TLS)和干净的关机处理,但如果您甚至不能进行最基本的点到点通信,谁在乎呢?)在

当然,您可以在websockets之上构建一个API,它公开面向连接且可靠(如TCP)但基于数据报(如UDP)的socket接口,然后假装您没有使用websockets……但是如果您正在寻找实时、低延迟的网络,则添加另一层使其很难接近金属当你发现你需要优化的东西时,尽可能多的不是一个好主意。或者,如果您想要这样做,我想您最好构建一个经过严格优化的网关,它将本地主机UDP与实际服务器通信,并将websockets与客户机进行通信。在


同时,您声称asyncio或{}

… isn't suitable because 1) network loop isn't going to be main loop here and 2) sockets are only used to transport data back and forth and nothing more.

1)asyncio和{}(尽管不是大多数其他网络库)都允许您从另一个循环中驱动它们的消息循环,只需手动运行循环的一次迭代,而不是永远运行。在

2)如何使用其他套接字,任何地方?在

我觉得Twisted可能是你需要的:

http://twistedmatrix.com/trac/export/29073/branches/websocket-4173-2/doc/web/howto/websocket.xhtml

下面是一篇关于它的深入文章,您想知道关于套接字的任何信息以及如何实现它们:

http://www.fullstackpython.com/websockets.html

我建议你仔细检查一下,然后再决定你想怎么做。我想说没有必要重新发明轮子,除非出于学术目的。使用现有的东西有助于更快地完成工作。手工操作也没有利用Python有如此强大的库这一事实。在

相关问题 更多 >

    热门问题