Python 中的 Socket.IO 客户端库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4762086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 17:24:02  来源:igfitidea点击:

Socket.IO Client Library in Python

pythonclient-serversocket.io

提问by Ada

Can anyone recommend a Socket.IO client library for Python? I've had a look around, but the only ones I can find are either server implementations, or depend on a framework such as Twisted.

谁能推荐一个用于 Python 的 Socket.IO 客户端库?我环顾四周,但我唯一能找到的要么是服务器实现,要么依赖于诸如 Twisted 之类的框架。

I need a client library that has no dependencies on other frameworks.

我需要一个不依赖于其他框架的客户端库。

Simply using one of the many connection types isn't sufficient, as the python client will need to work with multiple socketio servers, many of which won't support websockets, for example.

仅仅使用多种连接类型中的一种是不够的,因为 python 客户端需要使用多个 socketio 服务器,例如,其中许多不支持 websocket。

采纳答案by rmanna

Archie1986's answer was good but has become outdated with socketio updates (more specifically, its protocol : https://github.com/LearnBoost/socket.io-spec)... as far as i can tell, you need to perform the handshake manually before you can ask for a transport (e.g., websockets) connection... note that the code below is incomplete and insecure... for one, it ignores the list of supported transports returned in the handshake response and always tries to get a websocket... also it assumes that the handshake always succeeds... nevertheless, it's a good place to start

Archie1986 的回答很好,但随着 socketio 更新(更具体地说,它的协议:https: //github.com/LearnBoost/socket.io-spec)已经过时了......据我所知,你需要执行握手在请求传输(例如 websockets)连接之前手动手动... websocket...还假设握手总是成功...不过,这是一个很好的起点

import websocket, httplib

...

'''
    connect to the socketio server

    1. perform the HTTP handshake
    2. open a websocket connection '''
def connect(self) :
    conn  = httplib.HTTPConnection('localhost:8124')
    conn.request('POST','/socket.io/1/')
    resp  = conn.getresponse() 
    hskey = resp.read().split(':')[0]

    self._ws = websocket.WebSocket(
                    'ws://localhost:8124/socket.io/1/websocket/'+hskey,
                    onopen   = self._onopen,
                    onmessage = self._onmessage)

....

you might also want to read up on python-websockets: https://github.com/mtah/python-websocket

您可能还想阅读 python-websockets:https: //github.com/mtah/python-websockets

回答by Sylvain

Did you have a look at gevent-socketio?

你看过gevent-socketio吗?

Hope it helps.

希望能帮助到你。

回答by Archie1986

First of all, I'm not sure why some of your Socket.IO servers won't support websockets...the intent of Socket.IO is to make front-end browser development of web apps easier by providing an abstracted interface to real-time data streams being served up by the Socket.IO server. Perhaps Socket.IO is not what you should be using for your application? That aside, let me try to answer your question...

首先,我不知道为什么你的一些 Socket.IO 服务器不支持 websockets...Socket.IO 的目的是通过提供一个抽象的接口来使 web 应用程序的前端浏览器开发更容易。 - 由 Socket.IO 服务器提供的时间数据流。也许 Socket.IO 不是你应该为你的应用程序使用的?除此之外,让我试着回答你的问题......

At this point in time, there aren't any Socket.IO client libraries for Python (gevent-socketio is not a Socket.IO clientlibrary for Python...it is a Socket.IO serverlibrary for Python). For now, you are going to have to piece some original code together in order to interface with Socket.IO directly as a client while accepting various connection types.

目前,没有任何适用于 Python 的 Socket.IO 客户端库(gevent-socketio 不是适用于 Python的 Socket.IO客户端库……它是适用于 Python 的 Socket.IO服务器库)。现在,您必须将一些原始代码拼凑在一起,以便在接受各种连接类型的同时直接作为客户端与 Socket.IO 交互。

I know you are looking for a cure-all that works across various connection types (WebSocket, long-polling, etc.), but since a library such as this does not exist as of yet, I can at least give you some guidance on using the WebSocket connection type based on my experience.

我知道您正在寻找一种适用于各种连接类型(WebSocket、长轮询等)的万能药,但由于目前尚不存在此类库,因此我至少可以为您提供一些指导根据我的经验使用 WebSocket 连接类型。

For the WebSocket connection type, create a WebSocket client in Python. From the command line install this Python WebSocket Client package herewith pip so that it is on your python path like so:

对于 WebSocket 连接类型,在 Python 中创建一个 WebSocket 客户端。从命令行使用 pip在此处安装此 Python WebSocket Client 包,以便它位于您的 Python 路径上,如下所示:

pip install -e git+https://github.com/liris/websocket-client.git#egg=websocket

pip install -e git+https://github.com/liris/websocket-client.git#egg=websocket

Once you've done that try the following, replacing SOCKET_IO_HOSTand SOCKET_IO_PORTwith the appropriate location of your Socket.IO server:

一旦你已经做了尝试以下方法,替换SOCKET_IO_HOSTSOCKET_IO_PORT你Socket.IO服务器的适当位置:

import websocket

SOCKET_IO_HOST = "127.0.0.1"
SOCKET_IO_PORT = 8080

socket_io_url = 'ws://' + SOCKET_IO_HOST + ':' + str(SOCKET_IO_PORT) + '/socket.io/websocket'

ws = websocket.create_connection(socket_io_url)

At this point you have a medium of interfacing with a Socket.IO server directly from Python. To send messages to the Socket.IO server simply send a message through this WebSocket connection. In order for the Socket.IO server to properly interpret incoming messages through this WebSocket from your Python Socket.IO client, you need to adhere to the Socket.IO protocol and encode any strings or dictionaries you might send through the WebSocket connection. For example, after you've accomplished everything above do the following:

在这一点上,您有一个直接从 Python 与 Socket.IO 服务器接口的媒介。要将消息发送到 Socket.IO 服务器,只需通过此 WebSocket 连接发送消息即可。为了使 Socket.IO 服务器能够正确解释从 Python Socket.IO 客户端通过此 WebSocket 传入的消息,您需要遵守 Socket.IO 协议并对可能通过 WebSocket 连接发送的任何字符串或字典进行编码。例如,在完成上述所有操作后,请执行以下操作:

def encode_for_socketio(message):
    """
    Encode 'message' string or dictionary to be able
    to be transported via a Python WebSocket client to 
    a Socket.IO server (which is capable of receiving 
    WebSocket communications). This method taken from 
    gevent-socketio.
    """
    MSG_FRAME = "~m~"
    HEARTBEAT_FRAME = "~h~"
    JSON_FRAME = "~j~"

    if isinstance(message, basestring):
            encoded_msg = message
    elif isinstance(message, (object, dict)):
            return encode_for_socketio(JSON_FRAME + json.dumps(message))
    else:
            raise ValueError("Can't encode message.")

    return MSG_FRAME + str(len(encoded_msg)) + MSG_FRAME + encoded_msg

msg = "Hello, world!"
msg = encode_for_socketio(msg)
ws.send(msg)

回答by Amit Upadhyay

Wrote one: https://github.com/amitu/amitu-websocket-client/blob/master/amitu/socketio_client.py. It only supports websockets so it may have only marginal utility for you.

写了一篇:https: //github.com/amitu/amitu-websocket-client/blob/master/amitu/socketio_client.py。它只支持 websockets,所以它对你来说可能只有边际效用。

回答by Sushant Khurana

The SocketTornad.IOlibrary with the popular asynchronous Tornado Web Serveris also one of the options available for python.

带有流行的异步Tornado Web ServerSocketTornad.IO库也是 Python 可用的选项之一。

回答by Roy Hyunjin Han

The socketIO-clientlibrary supports event callbacks and channels thanks to the work of contributors and is available on PyPIunder the MIT license.

由于贡献者的工作,socketIO 客户端库支持事件回调和通道,并且在 MIT 许可下可在PyPI 上使用。

Emit with callback.

用回调发出。

from socketIO_client import SocketIO

def on_bbb_response(*args):
    print 'on_bbb_response', args

with SocketIO('localhost', 8000) as socketIO:
    socketIO.emit('bbb', {'xxx': 'yyy'}, on_bbb_response)
    socketIO.wait_for_callbacks(seconds=1)

Define events.

定义事件。

from socketIO_client import SocketIO

def on_aaa_response(*args):
    print 'on_aaa_response', args

socketIO = SocketIO('localhost', 8000)
socketIO.on('aaa_response', on_aaa_response)
socketIO.emit('aaa')
socketIO.wait(seconds=1)

Define events in a namespace.

在命名空间中定义事件。

from socketIO_client import SocketIO, BaseNamespace

class Namespace(BaseNamespace):

    def on_aaa_response(self, *args):
        print 'on_aaa_response', args
        self.emit('bbb')

socketIO = SocketIO('localhost', 8000)
socketIO.define(Namespace)
socketIO.emit('aaa')
socketIO.wait(seconds=1)

Define different namespaces on a single socket.

在单个套接字上定义不同的命名空间。

from socketIO_client import SocketIO, BaseNamespace

class ChatNamespace(BaseNamespace):

    def on_aaa_response(self, *args):
        print 'on_aaa_response', args

class NewsNamespace(BaseNamespace):

    def on_aaa_response(self, *args):
        print 'on_aaa_response', args

socketIO = SocketIO('localhost', 8000)
chatNamespace = socketIO.define(ChatNamespace, '/chat')
newsNamespace = socketIO.define(NewsNamespace, '/news')

chatNamespace.emit('aaa')
newsNamespace.emit('aaa')
socketIO.wait(seconds=1)