Skip to main content
 首页 » 编程设计

python之如何使用 "namespace"和参数连接到远程套接字服务器

2025年05月04日13cmt

我需要使用类似 ws://localhost:8006/user?id=666 的 url 从 python 客户端连接到 tornado 服务器。

我试过这样的:

import socket 
 
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect('ws://localhost:8006/user?id=666') 
print s.recv(1024) 
s.close 

...并出现以下错误:

TypeError: getsockaddrarg: AF_INET address must be tuple, not str 

谢谢

请您参考如下方法:

您不会连接到带有命名空间和参数的远程套接字。您连接主机和端口。时期。 Python 的 socket 模块是原生套接字的薄包装器。它对 http 或 ws 等协议(protocol)一无所知。

您可以连接到您的网络套接字使用的主机和端口。然后你可以发送任何你喜欢的参数......但它不会理解它们,除非你使用 websocket protocol .

最好的办法是使用其他人编写的 websocket 客户端(参见一些答案 here)

如果要自己写,here是一个最小的例子。