将Python客户机连接到套接字。io和定制的套接字。io事件

时间:2022-01-03 15:48:42

I have a socket.io server (in node.js) which I'm trying to connect a python client to, mainly to provide a command line interface to my socket server.

我有一个套接字。我正在尝试将python客户机连接到io服务器(node.js),主要是为了向我的套接字服务器提供命令行接口。

I'm using Python's web sockets, however, I've realised that this only supports four "events": on open, on close, on error and on message.

然而,我使用的是Python的web sockets,我意识到它只支持四个“事件”:打开、关闭、错误和消息。

My socket.io server defines custom events such as .on('connection'). How can I emit/receive such custom events in python?

我的套接字。io服务器定义自定义事件,如.on(“connection”)。如何在python中发出/接收此类自定义事件?

Here is my script so far, which just starts up and closes, and so it does not work. import web socket, requests, thread, time host = 'http://socket-url-server.com'

这是我到目前为止的脚本,它只是启动和关闭,所以它不起作用。导入web套接字、请求、线程、时间主机= 'http://socket-url-server.com'

def on_open(ws):
    def run(*args):
        print 'did connect'
        for i in range(3):
            time.sleep(1)
            result =  ws.recv()
            print 'received:'
            print result
        time.sleep(1)
        ws.close()
        print "thread terminating..."
    thread.start_new_thread(run, ())

def on_message(ws, message):
    print message

def on_error(ws, error):
    print error

def on_close(ws):
    print "### closed ###"

print('Connecting to %s' % host)

socket = host.replace('http://', 'ws://')
print socket
websocket.enableTrace(True)
_ws = websocket.WebSocketApp(socket,
                             on_message = on_message,
                             on_error = on_error,
                             on_close = on_close)
_ws.on_open = on_open
_ws.run_forever()

Which library / method should I use otherwise? If I do a handshake and grab the socket.io server key myself, how can I emit/receive events after that?

我应该使用哪个库/方法?如果我握手并抓住插座。io服务器密钥我自己,之后如何发送/接收事件?

I also tried using https://pypi.python.org/pypi/socketIO-client, but its documentation is very poor

我也尝试过使用https://pypi.python.org/pypi/socketio客户端,但是它的文档非常糟糕

I wrote the following script for it below but I get No handlers could be found for logger "socketIO_client" and it just hangs forever.

我为它编写了下面的脚本,但是我没有为logger“socketIO_client”找到任何处理程序,它只是永远挂起。

from socketIO_client import SocketIO, BaseNamespace

class Namespace(BaseNamespace):

    def on_connect(self):
        print '[Connected]'

socketIO = SocketIO('http://socket-server-url.com', 80, Namespace)
socketIO.wait(seconds=1)

1 个解决方案

#1


3  

I met the same question and have worked around this issue on my own. herein I wrote some comments regarding to usage of the library socketIO_client and hope it helps.

我遇到了同样的问题,我自己也解决了这个问题。在这里,我写了一些关于使用socketIO_client库的评论,希望它能有所帮助。

Developing environment: Server/Client: nodejs / sio_client written by python

开发环境:服务器/客户端:由python编写的nodejs / sio_client。

  1. "No handlers could be found for logger "socketIO_client". It means it needs handler for logging stuff. Try "import logging; logging.basicConfig(level=logging.DEBUG)" and it logged.
  2. 日志记录器“socketIO_client”没有任何处理程序。这意味着它需要处理程序来记录东西。尝试“进口记录;logging.basicConfig(水平= logging.DEBUG)”记录。
  3. "socketio_client hangs forever" since it keep reconnecting to the indicated server endlessly, i.e., Namespace object will not be adopted until socketIO object is initialized and returns. I have other thread (called thr_siohandle) which initializes the socketio object and main-thread take usage of queue included in Namespace so as to check if there's responses coming from server. It seems that your server should be accessible all the time before running your sio_client, otherwise it keeps re-connects unless you stop the program. Although you can set wait_for_connection as True to stop it, you must handle socketIO_client.exceptions.ConnectionError by yourself.
  4. “socketio_client永远挂起”,因为它不断地重新连接到指定的服务器,即。,在初始化并返回socketIO对象之前,不会采用名称空间对象。我有另一个线程(名为thr_siohandle),它初始化了socketio对象,而主线程利用了命名空间中包含的队列,以便检查是否有来自服务器的响应。似乎在运行sio_client之前,您的服务器应该是可访问的,否则它将继续重新连接,除非您停止程序。尽管可以将wait_for_connection设置为True以停止它,但是必须处理socketio_client .exception。自己ConnectionError。

FYI

仅供参考

[2014/02/19] Sorry, allow me to append some comments to my answers regarding to py_SIOClient.

[2014/02/19]对不起,请允许我就我对py_SIOClient的回答补充一些意见。

Example codes like this:

示例代码如下:

class ChatNamespace(BaseNamespace):
    def on_connect( self ):
        print "connected."
    def on_sayhello_response( self, data ):
        print "response:", data 

sio = SocketIO(host, port, ChatNamespace)
chatns = sio.define(ChatNamespace, '/chat')

while (1):
    chatns.emit('sayhello', {'name':'John'})
    chatns.wait(1)

Command 'sayhello' in this example will be inactive when the connection is reset, and the Namespace object chatns is no longer accessible (no error emerged either). Therefore, it could be worked around by re-defining the dedicated namespace every time before emitting message since we do not know whenever the connection will be reset (and it doesn't matter in my opinion). Hope it helps for people working on py_SocketIO_Client.

在此示例中,当连接重置时,命令“sayhello”将处于非活动状态,并且名称空间对象聊天将不再可访问(也没有出现错误)。因此,可以通过在发出消息之前重新定义专用的命名空间来解决这个问题,因为我们不知道什么时候连接将被重置(在我看来这并不重要)。希望这对在py_SocketIO_Client上工作的人有所帮助。

SUPPLEMENT 2014/09/09 As I used node(.js) as backend server, but this library seems not to be update for months and its socket.io supports only on socket.io < 1.0.0. Remind to check your package version please before you choosing this library. Hope it does help ppl facing same problem like mine.

补充2014/09/09,因为我使用node(.js)作为后端服务器,但是这个库似乎几个月都没有更新,它的套接字也没有更新。io只支持插座。io < 1.0.0。在您选择这个库之前,请提醒您检查您的软件包版本。希望它能帮助ppl公司面对和我一样的问题。

#1


3  

I met the same question and have worked around this issue on my own. herein I wrote some comments regarding to usage of the library socketIO_client and hope it helps.

我遇到了同样的问题,我自己也解决了这个问题。在这里,我写了一些关于使用socketIO_client库的评论,希望它能有所帮助。

Developing environment: Server/Client: nodejs / sio_client written by python

开发环境:服务器/客户端:由python编写的nodejs / sio_client。

  1. "No handlers could be found for logger "socketIO_client". It means it needs handler for logging stuff. Try "import logging; logging.basicConfig(level=logging.DEBUG)" and it logged.
  2. 日志记录器“socketIO_client”没有任何处理程序。这意味着它需要处理程序来记录东西。尝试“进口记录;logging.basicConfig(水平= logging.DEBUG)”记录。
  3. "socketio_client hangs forever" since it keep reconnecting to the indicated server endlessly, i.e., Namespace object will not be adopted until socketIO object is initialized and returns. I have other thread (called thr_siohandle) which initializes the socketio object and main-thread take usage of queue included in Namespace so as to check if there's responses coming from server. It seems that your server should be accessible all the time before running your sio_client, otherwise it keeps re-connects unless you stop the program. Although you can set wait_for_connection as True to stop it, you must handle socketIO_client.exceptions.ConnectionError by yourself.
  4. “socketio_client永远挂起”,因为它不断地重新连接到指定的服务器,即。,在初始化并返回socketIO对象之前,不会采用名称空间对象。我有另一个线程(名为thr_siohandle),它初始化了socketio对象,而主线程利用了命名空间中包含的队列,以便检查是否有来自服务器的响应。似乎在运行sio_client之前,您的服务器应该是可访问的,否则它将继续重新连接,除非您停止程序。尽管可以将wait_for_connection设置为True以停止它,但是必须处理socketio_client .exception。自己ConnectionError。

FYI

仅供参考

[2014/02/19] Sorry, allow me to append some comments to my answers regarding to py_SIOClient.

[2014/02/19]对不起,请允许我就我对py_SIOClient的回答补充一些意见。

Example codes like this:

示例代码如下:

class ChatNamespace(BaseNamespace):
    def on_connect( self ):
        print "connected."
    def on_sayhello_response( self, data ):
        print "response:", data 

sio = SocketIO(host, port, ChatNamespace)
chatns = sio.define(ChatNamespace, '/chat')

while (1):
    chatns.emit('sayhello', {'name':'John'})
    chatns.wait(1)

Command 'sayhello' in this example will be inactive when the connection is reset, and the Namespace object chatns is no longer accessible (no error emerged either). Therefore, it could be worked around by re-defining the dedicated namespace every time before emitting message since we do not know whenever the connection will be reset (and it doesn't matter in my opinion). Hope it helps for people working on py_SocketIO_Client.

在此示例中,当连接重置时,命令“sayhello”将处于非活动状态,并且名称空间对象聊天将不再可访问(也没有出现错误)。因此,可以通过在发出消息之前重新定义专用的命名空间来解决这个问题,因为我们不知道什么时候连接将被重置(在我看来这并不重要)。希望这对在py_SocketIO_Client上工作的人有所帮助。

SUPPLEMENT 2014/09/09 As I used node(.js) as backend server, but this library seems not to be update for months and its socket.io supports only on socket.io < 1.0.0. Remind to check your package version please before you choosing this library. Hope it does help ppl facing same problem like mine.

补充2014/09/09,因为我使用node(.js)作为后端服务器,但是这个库似乎几个月都没有更新,它的套接字也没有更新。io只支持插座。io < 1.0.0。在您选择这个库之前,请提醒您检查您的软件包版本。希望它能帮助ppl公司面对和我一样的问题。