套接字。Python中的IO客户端库

时间:2020-12-12 15:46:53

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的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服务器,例如,其中许多服务器不支持websockets。

6 个解决方案

#1


39  

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/pythonwebsocket

#2


24  

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...

首先,我不知道为什么有些插座。IO服务器不支持websockets…套接字的意图。IO是为了使前端浏览器开发的web应用程序更容易,通过提供一个抽象的接口,以实时数据流由套接字提供。IO服务器。也许插座。IO不是应用程序应该使用的吗?让我来回答你的问题……

At this point in time, there aren't any Socket.IO client libraries for Python (gevent-socketio is not a Socket.IO client library for Python...it is a Socket.IO server library 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的IO客户端库(gevent-socketio不是套接字)。Python的IO客户端库…这是一个套接字。用于Python的IO服务器库)。现在,您将不得不将一些原始代码拼凑在一起,以便与套接字进行交互。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、long-polling等)工作的灵丹妙药,但是由于目前还不存在这样的库,因此根据我的经验,我至少可以给您一些关于使用WebSocket连接类型的指导。

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

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

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

pip安装git - e + https://github.com/liris/websocket-client.git蛋= websocket

Once you've done that try the following, replacing SOCKET_IO_HOST and SOCKET_IO_PORT with the appropriate location of your Socket.IO server:

完成之后,请尝试以下操作,将SOCKET_IO_HOST和SOCKET_IO_PORT替换为套接字的适当位置。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:

此时,您就拥有了与套接字接口的介质。IO服务器直接来自Python。将消息发送到套接字。IO服务器只是通过这个WebSocket连接发送消息。为了插座。IO服务器通过这个WebSocket正确地解释来自Python套接字的传入消息。IO客户端,你需要坚持套接字。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)

#3


22  

The socketIO-client library supports event callbacks and channels thanks to the work of contributors and is available on PyPI under the MIT license.

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

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)

#4


5  

The SocketTornad.IO library with the popular asynchronous Tornado Web Server is also one of the options available for python.

SocketTornad。使用流行的异步旋风Web服务器的IO库也是python可用的选项之一。

#5


4  

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,所以它对你来说可能只有边际效用。

#6


2  

Did you have a look at gevent-socketio?

你看了gev -socketio吗?

Hope it helps.

希望它可以帮助。

#1


39  

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/pythonwebsocket

#2


24  

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...

首先,我不知道为什么有些插座。IO服务器不支持websockets…套接字的意图。IO是为了使前端浏览器开发的web应用程序更容易,通过提供一个抽象的接口,以实时数据流由套接字提供。IO服务器。也许插座。IO不是应用程序应该使用的吗?让我来回答你的问题……

At this point in time, there aren't any Socket.IO client libraries for Python (gevent-socketio is not a Socket.IO client library for Python...it is a Socket.IO server library 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的IO客户端库(gevent-socketio不是套接字)。Python的IO客户端库…这是一个套接字。用于Python的IO服务器库)。现在,您将不得不将一些原始代码拼凑在一起,以便与套接字进行交互。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、long-polling等)工作的灵丹妙药,但是由于目前还不存在这样的库,因此根据我的经验,我至少可以给您一些关于使用WebSocket连接类型的指导。

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

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

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

pip安装git - e + https://github.com/liris/websocket-client.git蛋= websocket

Once you've done that try the following, replacing SOCKET_IO_HOST and SOCKET_IO_PORT with the appropriate location of your Socket.IO server:

完成之后,请尝试以下操作,将SOCKET_IO_HOST和SOCKET_IO_PORT替换为套接字的适当位置。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:

此时,您就拥有了与套接字接口的介质。IO服务器直接来自Python。将消息发送到套接字。IO服务器只是通过这个WebSocket连接发送消息。为了插座。IO服务器通过这个WebSocket正确地解释来自Python套接字的传入消息。IO客户端,你需要坚持套接字。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)

#3


22  

The socketIO-client library supports event callbacks and channels thanks to the work of contributors and is available on PyPI under the MIT license.

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

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)

#4


5  

The SocketTornad.IO library with the popular asynchronous Tornado Web Server is also one of the options available for python.

SocketTornad。使用流行的异步旋风Web服务器的IO库也是python可用的选项之一。

#5


4  

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,所以它对你来说可能只有边际效用。

#6


2  

Did you have a look at gevent-socketio?

你看了gev -socketio吗?

Hope it helps.

希望它可以帮助。