Giter Site home page Giter Site logo

socketio-client's Introduction

image

socketIO-client

Here is a socket.io client library for Python. You can use it to write test code for your socket.io server.

Please note that this version implements socket.io protocol 1.x, which is not backwards compatible. If you want to communicate using socket.io protocol 0.9 (which is compatible with gevent-socketio), please use socketIO-client 0.5.7.2.

Installation

Install the package in an isolated environment. :

VIRTUAL_ENV=$HOME/.virtualenv

# Prepare isolated environment
virtualenv $VIRTUAL_ENV

# Activate isolated environment
source $VIRTUAL_ENV/bin/activate

# Install package
pip install -U socketIO-client

Usage

Activate isolated environment. :

VIRTUAL_ENV=$HOME/.virtualenv
source $VIRTUAL_ENV/bin/activate

Launch your socket.io server. :

cd $(python -c "import os, socketIO_client;\
    print(os.path.dirname(socketIO_client.__file__))")

DEBUG=* node tests/serve.js  # Start socket.io server in terminal one
DEBUG=* node tests/proxy.js  # Start proxy server in terminal two
nosetests                    # Run tests in terminal three

For debugging information, run these commands first. :

import logging
logging.getLogger('socketIO-client').setLevel(logging.DEBUG)
logging.basicConfig()

Emit. :

from socketIO_client import SocketIO, LoggingNamespace

with SocketIO('127.0.0.1', 8000, LoggingNamespace) as socketIO:
    socketIO.emit('aaa')
    socketIO.wait(seconds=1)

Emit with callback. :

from socketIO_client import SocketIO, LoggingNamespace

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

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

Define events. :

from socketIO_client import SocketIO, LoggingNamespace

def on_connect():
    print('connect')

def on_disconnect():
    print('disconnect')

def on_reconnect():
    print('reconnect')

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

socketIO = SocketIO('127.0.0.1', 8000, LoggingNamespace)
socketIO.on('connect', on_connect)
socketIO.on('disconnect', on_disconnect)
socketIO.on('reconnect', on_reconnect)

# Listen
socketIO.on('aaa_response', on_aaa_response)
socketIO.emit('aaa')
socketIO.emit('aaa')
socketIO.wait(seconds=1)

# Stop listening
socketIO.off('aaa_response')
socketIO.emit('aaa')
socketIO.wait(seconds=1)

# Listen only once
socketIO.once('aaa_response', on_aaa_response)
socketIO.emit('aaa')  # Activate aaa_response
socketIO.emit('aaa')  # Ignore
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('127.0.0.1', 8000, Namespace)
socketIO.emit('aaa')
socketIO.wait(seconds=1)

Define standard events. :

from socketIO_client import SocketIO, BaseNamespace

class Namespace(BaseNamespace):

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

    def on_reconnect(self):
        print('[Reconnected]')

    def on_disconnect(self):
        print('[Disconnected]')

socketIO = SocketIO('127.0.0.1', 8000, Namespace)
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('127.0.0.1', 8000)
chat_namespace = socketIO.define(ChatNamespace, '/chat')
news_namespace = socketIO.define(NewsNamespace, '/news')

chat_namespace.emit('aaa')
news_namespace.emit('aaa')
socketIO.wait(seconds=1)

Connect via SSL (#54). :

from socketIO_client import SocketIO

# Skip server certificate verification
SocketIO('https://127.0.0.1', verify=False)
# Verify the server certificate
SocketIO('https://127.0.0.1', verify='server.crt')
# Verify the server certificate and encrypt using client certificate
socketIO = SocketIO('https://127.0.0.1', verify='server.crt', cert=(
    'client.crt', 'client.key'))

Specify params, headers, cookies, proxies thanks to the requests library. :

from socketIO_client import SocketIO
from base64 import b64encode

SocketIO(
    '127.0.0.1', 8000,
    params={'q': 'qqq'},
    headers={'Authorization': 'Basic ' + b64encode('username:password')},
    cookies={'a': 'aaa'},
    proxies={'https': 'https://proxy.example.com:8080'})

Wait forever. :

from socketIO_client import SocketIO

socketIO = SocketIO('127.0.0.1', 8000)
socketIO.wait()

Don't wait forever. :

from requests.exceptions import ConnectionError
from socketIO_client import SocketIO

try:
    socket = SocketIO('127.0.0.1', 8000, wait_for_connection=False)
    socket.wait()
except ConnectionError:
    print('The server is down. Try again later.')

License

This software is available under the MIT License.

Credits

socketio-client's People

Contributors

adricepic avatar amfg avatar antonzy avatar asergi avatar bodgit avatar bradjc avatar burstaholic avatar danielquinn avatar drewhutchison avatar fcelda avatar fredericsureau avatar graingert avatar invisibleroads avatar jorgen-k avatar kengz avatar leth avatar lukasklein avatar robbieclarken avatar sarietta avatar stackmagic avatar thor27 avatar valhallasw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

socketio-client's Issues

SSLv3 alert bad record mac

@liris

Sporadically, nosetests produces the following warning when using the websocket transport to connect to an SSL server. It seems to be test-specific because the warning is associated with self-signed certificates.

_ssl.c:1419: error:140943FC:SSL routines:SSL3_READ_BYTES:sslv3 alert bad record mac

The particular test then fails because the transport session resets and socket.io keeps different sessions independent. This may be an issue with OpenSSL or one of the underlying libraries. I did not see this error with the polling transport.

If you know what is causing this issue, please add your comments here.

urlopen - Proxy

Hey,

first: thanks alot for developing and maintaining this package!
Similar to the secure flag could you add a property for setting a proxy? urlopen uses the IE Proxy setting on Windows as default which can be quite annoying.

Don't use any proxies
filehandle = urllib.urlopen(some_url, proxies={})

Thanks!

Client (master) does not reconnect after server failure

This is somewhat related to #53, but slightly different; #53 relates to the version on PyPI, which /does/ reconnect to the server, but which doesn't do a new namespace handshake. With master, this is what happens:

WARNING:socketIO_client:[connection error] connection closed ()
WARNING:socketIO_client:stream.wikimedia.org:80/socket.io/1: [connection error] connection closed ()
DEBUG:socketIO_client:ws://stream.wikimedia.org:80/socket.io/1/websocket/456634781549:  [disconnect]

and the client does not automatically reconnect. Is this something I'm supposed to handle manually (e.g. with on_disconnect), or is this a bug?

0.5.2 still times out too quick

Here is my code to initiate a socket connection:

socketIO = SocketIO(URL, 443, Namespace, verify=False)
socketIO.wait(seconds=5)

Here is my output (each output here is printed in at the end of an event):

Upgrading...
running                      
63  enqueued
63  running

Then it terminates. I have another web client in socket.io's client in JS, which works fine till the end and does not time out early.

When changing the wait to 10 seconds, the output becomes:

Upgrade Instance
running                      
63  enqueued
63  running
64  enqueued
64  running

As you can see, it ran a little longer and got more events.

It seems like the only solution is to set the wait to 200 seconds for me. However, if the job terminates before 200 seconds, it keeps connected until 200 seconds pass. Furthermore, if the job runs longer, then again it terminates before completion.

0.5.2 still times out too quickly. Is there anything special that needs to be configured in the server for 0.5.2 to not terminate too quick?

SocketIO.disconnect fail to disconnect

Lets say the current transport was disconnected for some reason and it will try to reconnect. Now at the same time if another thread calls SocketIO.disconnect, it checks the transport's connected property and it will simply return. But the reconnect is actually creating a new transport and will continue in wait loop.

Return args as a dict rather than a tuple

My nodejs websocket server is sending the following json args to my python client:

socket.emit("statusChanged", { motor: 'wrist', direction: 'up', id: '123' });

but I'm having trouble parsing it because it seems to be read as a tuple on the python end

botControl = socketIO.define(BotControl, '/bot')
socketIO.on('move', botControl.move)

class BotControl(BaseNamespace):

    def move(self, *args):
       print(args) --> output of this is ({u'direction': u'up', u'id': 0, u'motor': u'wrist'},)

Update: Me being an idiot sorry. Issue was not using args[0] and then dict() converting that. Ignore.

How to properly implement an async pub/sub client?

I have the following solution but it does not work very well. It does not seem to disconnect and is very slow on joining.

#!/usr/bin/env python


import time
import threading
from socketIO_client import SocketIO


class TestSubscribe():

    def connect(self):
        baseurl = "http://v1.livenet.bitcoin.chromanode.net"
        self._socketIO = SocketIO(baseurl, 80)
        self._socketIO.on('new-block', self.on_newblock)
        self._socketIO.emit('subscribe', 'new-block')
        self._socketIO_thread = threading.Thread(target=self._socketIO.wait)
        self._socketIO_thread.start()

    def on_newblock(self, blockid, blockheight):
        print "new-block:", blockid, blockheight
        # add to input queue for further processing

    def disconnect(self):
        # XXX works ... badly
        print "disconnect before:", self._socketIO.connected
        self._socketIO.disconnect()
        self._socketIO_thread.join() # takes quite some time
        print "disconnect after:", self._socketIO.connected # still connected?
        self._socketIO = None
        self._socketIO_thread = None


testsubscribe = TestSubscribe()
testsubscribe.connect()
time.sleep(10)
testsubscribe.disconnect()

Socket.IO v 1.0 is out

The latest stable Socket.IO is v1.0. This version changes the API, breaking this client.

crash on reconnect

Source code: https://github.com/huggle/XMLRCS/blob/master/src/ws2r/ws2r.py#L56

No handlers could be found for logger "socketIO_client"
Connecting
Reconnecting
Traceback (most recent call last):
  File "./ws2r.py", line 65, in <module>
    socketIO.wait()
  File "/home/petanb/Public/XMLRCS/src/ws2r/socketIO-client/socketIO_client/__init__.py", line 251, in wait
    self._process_events(timeout)
  File "/home/petanb/Public/XMLRCS/src/ws2r/socketIO-client/socketIO_client/__init__.py", line 268, in _process_events
    for packet in self._transport.recv_packet(timeout):
  File "/home/petanb/Public/XMLRCS/src/ws2r/socketIO-client/socketIO_client/__init__.py", line 332, in _transport
    socketIO_session, self._transport_name)
  File "/home/petanb/Public/XMLRCS/src/ws2r/socketIO-client/socketIO_client/__init__.py", line 380, in _get_transport
    }[transport_name](session, self.is_secure, self._base_url, **self._kw)
  File "/home/petanb/Public/XMLRCS/src/ws2r/socketIO-client/socketIO_client/transports.py", line 146, in __init__
    self._connection = websocket.create_connection(url, header=headers)
  File "/usr/local/lib/python2.7/dist-packages/websocket/_core.py", line 266, in create_connection
    websock.connect(url, **options)
  File "/usr/local/lib/python2.7/dist-packages/websocket/_core.py", line 524, in connect
    self._handshake(hostname, port, resource, **options)
  File "/usr/local/lib/python2.7/dist-packages/websocket/_core.py", line 596, in _handshake
    resp_headers = self._get_resp_headers()
  File "/usr/local/lib/python2.7/dist-packages/websocket/_core.py", line 549, in _get_resp_headers
    raise WebSocketException("Handshake status %d" % status)
websocket._exceptions.WebSocketException: Handshake status 502

I am calling self.emit on reconnect event but it causes the program to crash. Why? How do I implement proper reconnect to source

SocketIO.disconnect() fails to exit the wait loop

Issue #30 is closed with the remark "The client should now exit the loop if you explicitly ask it to disconnect"

Its not fixed. Calling disconnect actually disconnects and it raises a connection error. But since there is no check to identify that exception is raised because a forceful disconnection, the loop continues and creates a new connection in the next iteration. The transport property is actually creating a new transport if connected property is false. Checking for stop_waiting() inside connection exception should fix it.

Connecting to localhost fails.

Hi.

I have a trouble with connecting local server with socketIO-client.
socket.io server was running on node.js at localhost:3000 and I tried below python code as a client side to communicate with server by socket.io.

from socketIO_client import SocketIO
import logging

logging.basicConfig(level=logging.DEBUG)

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

with SocketIO(
    'localhost',
    3000,
    proxies={'http': 'http://xxxxx.xxx.xxxx.co.jp:10080'}
) as socketIO:
    socketIO.emit('message', {'value': 'Hey, from python'}, on_message_response)
    socketIO.wait_for_callbacks(seconds=1)

On connecting to server, below error occured. Is this a bug of socketIO-client? Or I've made some mistakes?

  • Ubuntu 12.04
  • python 2.7.5
  • socketIO-client 0.5.3

Thanks.

INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): xxxxx.xxx.xxxx.co.jp
DEBUG:requests.packages.urllib3.connectionpool:"GET http://localhost:3000/socket.io/1/ HTTP/1.1" 301 None
Traceback (most recent call last):
  File "socket_io_client_test.py", line 11, in <module>
    3000,
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/socketIO_client/__init__.py", line 136, in __init__
    self.define(Namespace)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/socketIO_client/__init__.py", line 150, in define
    namespace = Namespace(self._transport, path)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/socketIO_client/__init__.py", line 237, in _transport
    self.__transport = self._get_transport()
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/socketIO_client/__init__.py", line 251, in _get_transport
    self.is_secure, self.base_url, **self.kw)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/socketIO_client/__init__.py", line 399, in _get_socketIO_session
    response = _get_response(requests.get, server_url, **kw)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/socketIO_client/transports.py", line 309, in _get_response
    response = request(*args, **kw)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/api.py", line 55, in get
    return request('get', url, **kwargs)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/sessions.py", line 383, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/sessions.py", line 506, in send
    history = [resp for resp in gen] if allow_redirects else []
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/sessions.py", line 168, in resolve_redirects
    allow_redirects=False,
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/sessions.py", line 486, in send
    r = adapter.send(request, **kwargs)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/adapters.py", line 309, in send
    conn = self.get_connection(request.url, proxies)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/adapters.py", line 217, in get_connection
    conn = self.proxy_manager[proxy].connection_from_url(url)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/packages/urllib3/poolmanager.py", line 132, in connection_from_url
    u = parse_url(url)
  File "/home/hayashida/.pyenv/versions/2.7.5/lib/python2.7/site-packages/requests/packages/urllib3/util.py", line 397, in parse_url
    raise LocationParseError("Failed to parse: %s" % url)
requests.packages.urllib3.exceptions.LocationParseError: Failed to parse: Failed to parse: 2001:cf8:1:521:0:dddd:37fb:896c
Exception AttributeError: "'SocketIO' object has no attribute '_SocketIO__transport'" in <bound method SocketIO.__del__ of <socketIO_client.SocketIO object at 0x88ace2c>> ignored

Issue in Python3.3 and not in Python2.7

First, thank you so for writing this package! I appreciate your work and it has been very helpful.

I have a simple socket.io emitter and listener I wrote that has been running for the past 6 months ago or so. I upgraded python from 2.7 to 3.3 and am now getting an odd error. The pared down code is as follows:

Python socketio-client emitter is:

    from socketIO_client import SocketIO, LoggingNamespace

    rapidssl = '<dir>/GT_RapidSSL_SHA-2_under_SHA-1_root_bundle.crt'
    with SocketIO('https://<url>', 41777, LoggingNamespace, verify=rapidssl) as socketIO:
        socketIO.emit('test', {'param1': '1', 'param2': 2})
        socketIO.wait(seconds=1)
        socketIO.disconnect()

Node socket.io  listener:

    var http = require('https')
    var fs = require('fs')

    var options = {
      key: fs.readFileSync('key.pem'),
      cert: fs.readFileSync('cert.pem')
    };


    // Send index.html to all requests
    var server = http.createServer(options, function(req, res) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end('here' );

    });

    // Socket.io server listens to our server
    var io = require('socket.io').listen(server);

    // Emit welcome message on connection
    io.sockets.on('connection', function(socket) {
        process.stdout.write('=-----------------------------------------------\n');
        process.stdout.write('Got a connection\n');
        console.log(socket.name + ' ' + socket.id + ' ' + socket.handshake.headers.origin + ' ' + socket.handshake.address + ' ' + socket.handshake.headers);
        console.log( socket.handshake.headers );

        socket.on("test", function(msg) {
            var obj = eval(msg);
            process.stdout.write('Got a test for ' + obj.param1 + ' ' + obj.param2 + '\n');
        });


    });

    io.sockets.on('disconnect', function(socket) {
        process.stdout.write('Disconnected!!\n');
    });

    server.listen(41777);

When I run the first script with with Python2.7 everything works fine. No errors and I get the proper output from the socket.on("test"...) part.

When I run the code with Python3.3 then I get errors:

    socketIO_client.exceptions.ConnectionError: unexpected status code (400 {"code":1,"message":"Session ID unknown"})

The line in the socketIO-client python code is looking for a response of 200:

    if 200 != status_code:
        raise ConnectionError('unexpected status code (%s %s)' % (
            status_code, response.text))
    return response

It appears others have asked similar questions but I have not seen any responses that work. I have tried different machines, Python 3.3 and Python 3.4 and tried re-installing the node and socket.io via npm but to no avail. The really weird thing is that 1 in 10 times I run it in Python 3.3 it works. The other 9/10 times I get the above error.

Any ideas would be appreciated.

Timeout Problems

In writing a simple client for a NodeJS server, I've found that I connect, receive a message from the server, and then immediately get a WebSocketTimeoutException. It appears the client timeout (2 seconds) is far too short.

If I import transports and set TIMEOUT_IN_SECONDS to, say, 60, then my connection hangs around long enough for the server to timeout and disconnect from its end.

It appears that the heartbeat mechanism is not functioning correctly; is there something I'm not setting up?

Self Signed SSL Cert with socketIO

Hi.

I am trying to get socketio-client to connect to a local node.js server.

If I run straight http everything is fine.

If I attempt to access the server using https with Self Signed Certs I run into problems.
(I have a working python example connection to the server using urllib2 to post a JSON document so I am fairly sure it all works together.)

I want to use a self signed cert against node.js on my local machine (CN of the cert is the eventual domain)

If I specify a .pem file i.e.
verify='....../certs/server/server.pem'

with SocketIO('https://127.0.0.1:8443',
verify=verify,
cert=('certs/monitor/monitor.crt', 'certs/monitor/monitor.key')) as socketIO:

I get WARNING:socketIO_client:[waiting for connection] hostname '127.0.0.1' doesn't match u'

so its doing CN checking - can we disable this? I have started looking into the urllib3 connectionPooling code as there is an assert_hosts=False flag which should be applicable. However I cannot seem to make this work with socketIO.

If I use verify=False i.e.
SocketIO('https://127.0.0.1:8443',
verify=False,
cert=('certs/monitor/monitor.crt', 'certs/monitor/monitor.key')) as socketIO:

Then I get

WARNING:socketIO_client:[waiting for connection] [Errno 1] _ssl.c:510: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

So it looks like verify is NOT being passed through successfully

in either case it seems to go into a loop attempting to access 127.0.0.1

Any help would be useful.

Excellent apart from that........

Namespace on_connect called 2 times

It seems that the on_connect callback is called 2 times. First time just after sending 1::/path, second time after receiving 1::/path acknowledgment.

On line 148, on_connect is called just after Namespace instanciation. Is it the desired behavior ?

Here is the log of my code:

INFO:requests.packages.urllib3.connectionpool:Starting new HTTP connection (1): myserver.com
DEBUG:requests.packages.urllib3.connectionpool:"GET /socket.io/1/ HTTP/1.1" 200 None
DEBUG:socketIO_client:[transports available] websocket flashsocket htmlfile xhr-polling jsonp-polling
DEBUG:socketIO_client.transports:[transport selected] websocket
DEBUG:socketIO_client: [connect]
DEBUG:socketIO_client.transports:[packet sent] 1::/operations:
DEBUG:socketIO_client:/operations [connect]
DEBUG:socketIO_client.transports:[packet received] 1::
DEBUG:socketIO_client: [connect]
DEBUG:socketIO_client.transports:[packet sent] 2:::
DEBUG:socketIO_client.transports:[packet received] 1::/operations
DEBUG:socketIO_client:/operations [connect]

websocket 0.2.1 ; object has no attribute 'create_connection'

If pypi package 'websocket' is installed, a backtrace results:

File "build/bdist.linux-i686/egg/socketIO_client/init.py", line 156, in init
self.define(Namespace)
File "build/bdist.linux-i686/egg/socketIO_client/init.py", line 174, in define
namespace = Namespace(self._transport, path)
File "build/bdist.linux-i686/egg/socketIO_client/init.py", line 263, in _transport
self.__transport = self._get_transport()
File "build/bdist.linux-i686/egg/socketIO_client/init.py", line 287, in _get_transport
self.is_secure, self.base_url, **self.kw)
File "build/bdist.linux-i686/egg/socketIO_client/transports.py", line 295, in _negotiate_transport
}[supported_transport](session, is_secure, base_url, **kw)
File "build/bdist.linux-i686/egg/socketIO_client/transports.py", line 128, in init
self._connection = websocket.create_connection(url)
AttributeError: 'module' object has no attribute 'create_connection'

this is https://pypi.python.org/pypi/websocket, by @denik

Don't Reconnect to Blank Namespace Unconditionally

I've noticed that if the socket.io connection is disconnected and then reconnects, the client connects to the blank namespace (path==''), even if that wasn't specified as a namespace at the beginning. The reason is this line:

class SocketIO(object):
    def __init__(
         ...
         self.define(Namespace)

in the constructor. Adding that namespace adds it to the list of namespaces, and therefore causes it to be connected when the socket.io connection is reestablished. The default blank namespace should be changed so this default connection doesn't happen.

Python 3 support for socketIO-client 0.5.6

As mentioned on PyPi page here, socketIO-client supports Python 3.4 since version 0.5.5. but when I tried to run a simple example with Python 3.4, It showed following error when socketIO.wait() method was called.
error

License?

This looks spiffy. What license are you distributing it under?

Not an issue, just a question about threading

Great library, really helped us out. Moreover, it's eased our transition from Ruby to Python :)

We ran into a problem with the fact it's using threading to 'process' the messages returned from the server. Because of the embedded devices we're running this on right now, the memory usage has hit the ceiling at a min. of 39%. Yeah, sounds high but we're working with 32mb!

So, we looked writing something in c++ but that's a no go right now and we'd like to push this a little further.

Do you see any way we can write this without threads or at least, reduce the usage a little?

I have a non threaded websocket client running in Python that's on about 23%. That's actually achievable, I just don't see how we'd get the messages.

Simon

Version >0.5.5 not working with gevent-socketio

Just found, that while version >0.5.5 implements SocketIO protocol version 1.x, it won't work with gevent-socketio server. That's not the socketIO-client's fault, but it takes me quite a lot of time to realize this, so, maybe it can be useful for someone else.

Add 0.3 tag

Hi,

Can you add a 0.3 tag pointing to the latest commit?

Thanks.

Secure connection support

Hi,

Thanks for developing this library. If it's not trouble you to much, could you add a flag in constructor to support secure connection protocol like "https://" and "wss://" in the client.

Thank you.

testsuite, how to run

Taking the last release -0.5.6 released the same day as -0.6.5

  1. on running it it objects to the local import structure in the init.py
    (from .. import SocketIO, LoggingNamespace, find_callback)
    which might work once installed.
  2. On changing that to an abs path:
  3. It complete running with
python socketIO_client /tests/__init__.py

with nil output to the screen

  1. Using
nosetests socketIO_client /tests/__init__.py 

it then simply hangs.

Is it a normal testsuite? When there is no output to tty it generally means the tests were no actually run. They require the output to confirm that something actually happened. This just leaves total doubt

How to create a pub/sub client?

I've been trying to implement the python equivalent of the code below but cannot seem to get it working.

var io = require('socket.io-client')
var socket = io('http://devel.hz.udoidio.info:5000')

socket.on('connect', function () {
  socket.emit('subscribe', 'new-tx')
})

socket.on('new-tx', function (txid) {
  console.log('New tx: ' + txid)
})

I tried this approach but it does not seem to yield anything.

from socketIO_client import SocketIO, LoggingNamespace

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

baseurl = "http://v1.livenet.bitcoin.chromanode.net"
socketIO = SocketIO(baseurl, 80, LoggingNamespace)
socketIO.on('subscribe', on_response)
socketIO.emit('subscribe', 'new-block')
socketIO.wait()

Improve object cleanup when connection fails

When wrapping a socket connection in a try, so an exception can be caught if the connection can't be made because the socket server is unreachable, e.g.
try:
ws = SocketIO('localhost', 8080, wait_for_connection=False)
except:
handle_exception()

An uncaught exception occurs:
Exception ignored in: bound method SocketIO.del of <socketIO_client.SocketIO object at 0x7f9be435efd0

This is because errors raised by del output to stderr and are not caught.
The cause of this looks to be in _close() when halt() is called on _heartbeat_thread This is because there is no _heartbeat_thread for the object as an exception occurred during initialization.

A suggested solution is to wrap the halt() call in a try block, e.g.
try:
self._heartbeat_thread.halt()
except:
pass

I haven't made a pull request with this as the solution as the author may not want this behavior, so I wanted to check first

Backport for requests 0.8.2?

I want to backport socketIO_client 0.5.3 from Ubuntu Utopic to Precise (cf. https://bugs.launchpad.net/precise-backports/+bug/1458651). Ubuntu Precise ships requests 0.8.2 which makes my test script (from https://wikitech.wikimedia.org/wiki/RCStream#Python):

import socketIO_client

class WikiNamespace(socketIO_client.BaseNamespace):
    def on_change(self, change):
        print('%(user)s edited %(title)s' % change)

    def on_connect(self):
        self.emit('subscribe', 'commons.wikimedia.org')


socketIO = socketIO_client.SocketIO('stream.wikimedia.org', 80)
socketIO.define(WikiNamespace, '/rc')

socketIO.wait()

fail with:

scfc@toolsbeta-test-precise:~$ bin/socketio_client-test.py 
Traceback (most recent call last):
  File "bin/socketio_client-test.py", line 13, in <module>
    socketIO = socketIO_client.SocketIO('stream.wikimedia.org', 80)
  File "/usr/lib/python2.7/dist-packages/socketIO_client/__init__.py", line 136, in __init__
    self.define(Namespace)
  File "/usr/lib/python2.7/dist-packages/socketIO_client/__init__.py", line 150, in define
    namespace = Namespace(self._transport, path)
  File "/usr/lib/python2.7/dist-packages/socketIO_client/__init__.py", line 237, in _transport
    self.__transport = self._get_transport()
  File "/usr/lib/python2.7/dist-packages/socketIO_client/__init__.py", line 251, in _get_transport
    self.is_secure, self.base_url, **self.kw)
  File "/usr/lib/python2.7/dist-packages/socketIO_client/__init__.py", line 402, in _get_socketIO_session
    response_parts = response.text.split(':')
AttributeError: 'Response' object has no attribute 'text'
Exception AttributeError: "'SocketIO' object has no attribute '_SocketIO__transport'" in <bound method SocketIO.__del__ of <socketIO_client.SocketIO object at 0x1723310>> ignored
scfc@toolsbeta-test-precise:~$

To fix this, I replaced the references to response.text in __init__.py and transports.py with response.content (cf. e2d9242). With that, my test script succeeds, but I'm lacking the insight if this is a universal solution or only works for my specific test case.

So before I proceed with pushing this to Ubuntu Precise, I'd like to solicit some input/test cases/confirmation/etc. if this is a reasonable fix.

Unicode payload causing crash -- UnicodeEncodeError with six.py

Hey all,

I'm connecting to a server that is sending back messages containing Unicode characters and as a result I run into the following error:

$ python go.py
Connected!
Traceback (most recent call last):
  File "go.py", line 21, in <module>
    socketIO.wait()
  File "c:\Python34\lib\site-packages\socketIO_client\__init__.py", line 232, in
 wait
    self._process_packets()
  File "c:\Python34\lib\site-packages\socketIO_client\__init__.py", line 254, in
 _process_packets
    for engineIO_packet in self._transport.recv_packet():
  File "c:\Python34\lib\site-packages\socketIO_client\transports.py", line 155,
in recv_packet
    six.b(packet_text))
  File "c:\Python34\lib\site-packages\six.py", line 597, in b
    return s.encode("latin-1")
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2605' in position
93: ordinal not in range(256)

The problem character appears to be a "BLACK STAR"

I'm using...

  • Python 3.4.3
  • socketIO-client 0.6.5
  • six 1.9.0
  • Windows 7
  • "Git Bash" (Msysgit)

As an added curiosity: adding a print(s) in six.py before return s.encode("latin-1") causes it to not fail. No idea.

Any help appreciated.

PEP 440 package naming & versioning

builds using this package report a warning for every release, including 0.5.3

PEP440Warning: 'socketIO (client-0.5.3)' is being parsed as a legacy, non PEP 440, version. You may find odd behavior and sort order. In particular it will be sorted as less than 0.0. It is recommend to migrate to PEP 440 compatible versions.

See e.g.

https://travis-ci.org/jayvdb/pywikibot-core/jobs/50130757

And the same issue raised with websocket-client
websocket-client/websocket-client#147

SocketIO never connecting

Hi,

I have a program using your client that runs fine on my box. Running it to another box however, it fails. They both run Python2.7 and are on socketIO-client 0.5.3.

The one that fails shows this:

socket host: https://16.tasker-api.mgmt.nym2.adnexus.net
INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): tasker.adnxs.net
DEBUG:requests.packages.urllib3.connectionpool:"GET /socket.io/1/ HTTP/1.1" 200 None
DEBUG:socketIO_client:[transports available] websocket htmlfile xhr-polling jsonp-polling
DEBUG:socketIO_client.transports:[transport selected] websocket
DEBUG:socketIO_client.transports:[packet received] 7:::1+0
INFO:socketIO_client: [error] 0
WARNING:socketIO_client:[connection error] connection closed ()
DEBUG:socketIO_client: [disconnect]

and then subsequently it keeps showing this forever:

INFO:requests.packages.urllib3.connectionpool:Starting new HTTPS connection (1): tasker.adnxs.net
DEBUG:requests.packages.urllib3.connectionpool:"GET /socket.io/1/ HTTP/1.1" 200 None
DEBUG:socketIO_client:[transports available] websocket htmlfile xhr-polling jsonp-polling
DEBUG:socketIO_client.transports:[transport selected] websocket
DEBUG:socketIO_client.transports:[packet received] 7:::1+0
INFO:socketIO_client: [error] 0
DEBUG:socketIO_client: [disconnect]

How can I debug this? What else could it be? It is working on a CentOS 5.6 box and failing on a CentOS 5.8 box.

Thank you

Unable to handle invalid namespace

We have the occasional timing issue where the python client attempts to connect to a namespace before it has been created (from an action of another client). The SocketIO server logs the following:

socket.io:server incoming connection with id WvR6SwDvKMssDHf2AUFD
socket.io:client connecting to namespace /
socket.io:namespace adding socket to nsp /
socket.io:socket socket connected - writing packet
socket.io:socket joining room WvR6SwDvKMssDHf2AUFD
socket.io:client writing packet {"type":0,"nsp":"/"}
socket.io-parser encoding packet {"type":0,"nsp":"/"}
socket.io-parser encoded {"type":0,"nsp":"/"} as 0
socket.io:socket joined room WvR6SwDvKMssDHf2AUFD
socket.io-parser decoded 0/custom-namespace, as {"type":0,"nsp":"/custom-namespace"}
socket.io:client connecting to namespace /custom-namespace
socket.io:client writing packet {"type":4,"nsp":"/custom-namespace","data":"Invalid namespace"}
socket.io-parser encoding packet {"type":4,"nsp":"/custom-namespace","data":"Invalid namespace"}
socket.io-parser encoded {"type":4,"nsp":"/custom-namespace","data":"Invalid namespace"} as 4/custom-namespace,"Invalid namespace"

However, this appears to cause the python client to hang. I have wrapped the connection in a try but it hasn't helped. I cannot see any code to deal with invalid namespaces and cant work out how to handle it in my code.

What is the best way to deal with connecting to an invalid namespace?

Many thanks

Emit at variable rate but still detect disconnections

This may be an issue, but it may also just be a question.

How would one emit to a socket at a variable rate (i.e. based on user input or something similar) but still use wait to handle disconnections and reconnections? When the socket is waiting, it cannot emit anything, but if you don't wait, you don't capture the heartbeats and disconnections. Am I missing something?

SSL connect/disconnect loop

Hi,

I'm experiencing the following only thru ssl , http connections are fine. but when connecting thru ssl I get disconnected saying "WARNING:root:iot.myHost.io:3001/socket.io [connection error] recv disconnected by SSL (('The read operation timed out',))" for every time that I execute socketIO.wait(seconds=1). I have tried running my socket.io server as http and using nginx for the ssl and also running native node https server both have same results. It would be great help any feedback.

BTW SSL works fine for everything else, certificate seems to be good. as I can curl and see correct response.

Im running socketIO-client on python 2.7.9 but it does same on 2.7.3 on raspbian.

socket.io server debug

This is log form socket.io, this is repeated for every socketIO.wait :
App connected
socket.io:socket joining room cloud +1ms
socket.io:socket joined room mGZgzNZ6gsAqycLoAAAF +0ms
socket.io:socket joined room cloud +0ms
engine upgrading existing transport +754ms
engine:socket might upgrade socket transport from "polling" to "websocket" +0ms
engine:ws received "2probe" +89ms
engine:ws writing "3probe" +0ms
engine:ws received "5" +100ms
engine:socket got upgrade packet - upgrading +0ms
engine:socket flushing buffer to transport +0ms
engine:ws writing "40" +0ms
engine:ws received "2" +1ms
engine:socket packet +0ms
engine:socket got ping +0ms
engine:socket sending packet "pong" (undefined) +0ms
engine:socket flushing buffer to transport +1ms
engine:ws writing "3" +0ms
socket.io:client client close with reason transport close +6s
socket.io:socket closing socket - reason transport close +1ms
socket.io:client ignoring remove for 0SV7_KSjY9OAc79rAAAE +0ms
Cloud App Dissconnected
socket.io:client client close with reason transport close +48ms
socket.io:socket closing socket - reason transport close +1ms
socket.io:client ignoring remove for mGZgzNZ6gsAqycLoAAAF +0ms

Socket.IO server :

var fs = require('fs');
var options = {
key: fs.readFileSync('/opt/certs/iot.myhost.io.key'),
cert: fs.readFileSync('/opt/certs/iot.myhost.io.chained.crt')
};
var app = require('https').createServer(options,handler)
var io = require('socket.io')(app);
app.listen(3001);

Python raspbian client

socketIO = SocketIO('https://iot.myhost.io,3001, params={"myID":'898989898',"type":"CLIENT"})
socketIO.on('on_test', on_test_response)
socketIO.wait(seconds=1)

Thanks,
Ray

Continued development?

We have been using this package for a while, but have noticed the project seems to have stalled of late so wanted to check whether further development / merging of pull requests is planned?

If not, we would be happy to take over maintenance and further development of the project - let me know.

cheers,

Martin

Cannot import name SocketIO

I was trying to use socketIO_client but always getting this error:

"from socketIO_client import SocketIO
ImportError: cannot import name SocketIO"

Early Time Out for long waits

For one of the events, my server doesn't send data for quite a while (usually 1 - 2 minutes), and sometimes longer. It seems that I need to set my self.wait(seconds=) value to the maximum possible "waiting" period, which is impossible/inaccurate.

My other client that uses socket.io's library in JS as a client, does not have this problem. It seems that the server is sending appropriate heartbeats and that client is working fine with them,

Is there a way to "wait" for these long timeouts? How are heartbeats handled here? Here is how I'm doing the wait:

socketIO = SocketIO(URL, 443, Namespace, secure=True, wait_for_connection=True)
socketIO.wait(seconds=200)

This long wait always happens at an event called task_log_delta. I tried calling self.wait there but it is undefined under the class Namespace.

Server failure unhandled

If a server and client make a connection, and then the server restarts, the client fails to successfully reconnect.

On the lower level, the client believes that it has connected again and receives heartbeats from the server, but the server never receives a connection request. On the client side, I have no notification that anything is wrong. No disconnect callback occurs since the connection was forcibly reset. This means the client sits in recv() waiting for data that the server doesn't know to give it.

To demonstrate this problem: start a server and client with a valid connection, kill the server, restart the server. The client will fail to successfully reconnect.

Fixing reconnections to the server would be useful. Alternatively, if the user was given some type of exception or callback that a disconnect had occurred, they could deal with it themselves. Trying automatically and silently to reconnect to the server and failing is a problem.

Client not connecting to a socket.io server

I have a server running socket.io on port 80. It works perfectly fine with another client that is written using socket.io's client in Javascript. Now I am trying to write a Python client for that server using this library.

Following the instructions, here's my code:

from socketIO_client import SocketIO, BaseNamespace
class Namespace(BaseNamespace):
    def on_connect(self):
        print('Connected')

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

However, I get an error: No handlers could be found for logger "socketIO_client" and nothing happens when the server connects and starts emitting.

Am I missing something here? I also tried including the /socket.io/1 to the URL but that did not work either.

Thanks,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.