Giter Site home page Giter Site logo

websocket-client / websocket-client Goto Github PK

View Code? Open in Web Editor NEW
3.5K 86.0 757.0 1.44 MB

WebSocket client for Python

Home Page: https://github.com/websocket-client/websocket-client

License: Apache License 2.0

Python 100.00%
websocket websockets websocket-client websockets-client python rfc-6455

websocket-client's Introduction

docs Build Status codecov PyPI Downloads PyPI version License Code style: black

websocket-client

websocket-client is a WebSocket client for Python. It provides access to low level APIs for WebSockets. websocket-client implements version hybi-13 of the WebSocket protocol. This client does not currently support the permessage-deflate extension from RFC 7692.

Documentation

This project's documentation can be found at https://websocket-client.readthedocs.io/

Contributing

Please see the contribution guidelines

Installation

You can use pip install websocket-client to install, or pip install -e . to install from a local copy of the code. This module is tested on Python 3.8+.

There are several optional dependencies that can be installed to enable specific websocket-client features.

  • To install python-socks for proxy usage and wsaccel for a minor performance boost, use: pip install websocket-client[optional]
  • To install websockets to run unit tests using the local echo server, use: pip install websocket-client[test]
  • To install Sphinx and sphinx_rtd_theme to build project documentation, use: pip install websocket-client[docs]

While not a strict dependency, rel is useful when using run_forever with automatic reconnect. Install rel with pip install rel.

Footnote: Some shells, such as zsh, require you to escape the [ and ] characters with a \.

Usage Tips

Check out the documentation's FAQ for additional guidelines: https://websocket-client.readthedocs.io/en/latest/faq.html

Known issues with this library include lack of WebSocket Compression support (RFC 7692) and minimal threading documentation/support.

Performance

The send and validate_utf8 methods can sometimes be bottleneck. You can disable UTF8 validation in this library (and receive a performance enhancement) with the skip_utf8_validation parameter. If you want to get better performance, install wsaccel. While websocket-client does not depend on wsaccel, it will be used if available. wsaccel doubles the speed of UTF8 validation and offers a very minor 10% performance boost when masking the payload data as part of the send process. Numpy used to be a suggested performance enhancement alternative, but issue #687 found it didn't help.

Examples

Many more examples are found in the examples documentation.

Long-lived Connection

Most real-world WebSockets situations involve longer-lived connections. The WebSocketApp run_forever loop will automatically try to reconnect to an open WebSocket connection when a network connection is lost if it is provided with:

  • a dispatcher argument (async dispatcher like rel or pyevent)
  • a non-zero reconnect argument (delay between disconnection and attempted reconnection)

run_forever provides a variety of event-based connection controls using callbacks like on_message and on_error. run_forever does not automatically reconnect if the server closes the WebSocket gracefully (returning a standard websocket close code). This is the logic behind the decision. Customizing behavior when the server closes the WebSocket should be handled in the on_close callback. This example uses rel for the dispatcher to provide automatic reconnection.

import websocket
import _thread
import time
import rel

def on_message(ws, message):
    print(message)

def on_error(ws, error):
    print(error)

def on_close(ws, close_status_code, close_msg):
    print("### closed ###")

def on_open(ws):
    print("Opened connection")

if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("wss://api.gemini.com/v1/marketdata/BTCUSD",
                              on_open=on_open,
                              on_message=on_message,
                              on_error=on_error,
                              on_close=on_close)

    ws.run_forever(dispatcher=rel, reconnect=5)  # Set dispatcher to automatic reconnection, 5 second reconnect delay if connection closed unexpectedly
    rel.signal(2, rel.abort)  # Keyboard Interrupt
    rel.dispatch()

Short-lived Connection

This is if you want to communicate a short message and disconnect immediately when done. For example, if you want to confirm that a WebSocket server is running and responds properly to a specific request.

from websocket import create_connection

ws = create_connection("ws://echo.websocket.events/")
print(ws.recv())
print("Sending 'Hello, World'...")
ws.send("Hello, World")
print("Sent")
print("Receiving...")
result =  ws.recv()
print("Received '%s'" % result)
ws.close()

websocket-client's People

Contributors

allanlewis avatar bubbleboy14 avatar carlwgeorge avatar cdare avatar damjanstulicsonos avatar dimaqq avatar eendebakpt avatar ekeydar avatar engn33r avatar graingert avatar grintor avatar hugovk avatar imba-tjd avatar instance01 avatar j-a-n avatar jayvdb avatar kenjitakahashi avatar krosinski avatar liris avatar louisliu avatar marenthyu avatar minus7 avatar mjhanninen avatar mottl avatar nlevitt avatar ralphbean avatar seratch avatar sim6 avatar ukwksk avatar yukiwakisaka 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  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

websocket-client's Issues

Default WebSocket Connection Timeout with Microsoft.WebSockets

I'm using Microsoft.WebSockets on my server. When I form a WebSocket with a browser (without any ping messages), the connection with the server lasts at least 12 hours (which is as much I've tested). But with your Python WebSocket client, it seems to disconnect at 31 minutes, 13 seconds. I've repeatedly tested at 31 minutes and 12 seconds, and it still works, but at 31 minutes and 13 seconds, the connection is dead. Why would this be?
In the meantime, I just make sure to ping every 30 minutes, and the connection stays alive.
(By the way, this project is pretty cool. Thank you!)

'websocket' clashes with other popular python libraries

''websocket' is quite a generic, all-encompassing name for a package that is only a client and causes issues when using other websocket libraries (.e.g. those that provide a server implementation) in the same python installation.

URL parsing is broken

With Python 2.5 and 2.6, url parsing is broken because urlparse doesn't know how to interpret the ws scheme. Here's a fixed version that works correctly:

def _parse_url(url):
    """
    parse url and the result is tuple of 
    (hostname, port, resource path and the flag of secure mode)
    """
    if ":" not in url:
        raise ValueError("url is invalid")

    scheme, url = url.split(":", 1)
    url = url.rstrip("/")

    parsed = urlparse(url, scheme="http")
    if parsed.hostname:
        hostname = parsed.hostname
    else:
        raise ValueError("hostname is invalid")
    port = 0
    if parsed.port:
        port = parsed.port

    is_secure = False
    if scheme == "ws":
        if not port:
            port = 80
    elif scheme == "wss":
        is_secure = True
        if not port:
            port  = 443
    else:
        raise ValueError("scheme %s is invalid" % scheme)

    if parsed.path:
        resource = parsed.path
    else:
        resource = "/"

    return (hostname, port, resource, is_secure)

IPv6 socket support

Currently using IPv6 is not possible, because an IPv4 socket will be created explicitely.

self.sock = socket.socket()
...
self.sock.connect((hostname, port))

To enable IPv6 we need to something like

# parse/check if ipv6 is possible/prefered
self.sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM, 0)
...
addrinfo = socket.getaddrinfo("myipv6capabledomain.com", 80, 0, 0, socket.SOL_TCP)
# [(2, 1, 6, '', ('82.94.164.162', 80)),
#  (10, 1, 6, '', ('2001:888:2000:d::a2', 80, 0, 0))]
self.sock.connect(('2001:888:2000:d::a2', 80, 0, 0))

PyPI tarball is missing test_websocket.py

Hi,

I'm doing some QA of this module in Ubuntu, which is coming into Ubuntu through the Debian package, which is based on the PyPI tarball.

We have a policy of automatically running upstream tests when our packages are built where possible. We can't do that with this module, since the tests are missing from the Python sdist tarball.

Please can you add the file to the PyPI tarball distribution, so that others can also run your tests? I think you can do this by tweaking setup.py to include it.

Thanks!

Setting Ping Message : Please advice

Dear Author,

Is there a way I can send "IAM ALIVE" message regularly along with ping. My aim is to send heartbeat to the server that my application is alive.

Also, as per your advice, I set the following code.

ws.run_forver( ping_interval=30, ping_timeout=10) This goes to On_error after sending the first message and When I unplug the network cable this still does not raise error after 10 seconds as set by timeout.

Look forward to your advice.

Thank you sir.

BRE

Lack of setup.cfg file prevents trivial debianising

Hi,

Great library. I'm debianising a few python libraries, since we using debians packaging for maintaining machines. If you add in a default set.cfg file, this is simple as this:

python setup.py sdist
cd dist
py2dsc websocket-client-0.12.0.tar.gz
cd deb_dist
cd websocket-client-0.12.0
debuild -uc -us

(Package is now in directory above)

However, this only succeeds if I add in a setup.cfg file. I've forked the project and added the file and will put in place a pull request - but thought putting an issue in as well about it might be the friendly thing to do :-)

Thanks!

Keepalive / ping ?

Hello,

I see that there is a ping function, but could you integrate this into perhaps run_forever as a keepalive ? Forgive me if this isn't the proper way to handle this. For simple code using run_forever, I don't see a way to keep the socket open. An option for run_forever (or somewhere else) to set the connection to keepalive (with a configureable ping interval).

Thanks.

Sinatra docs

This would be uber-useful. If you happen to know off the top of your head, beers/drugs/candy are yours!

You can close this if you don't though :)

TypeError in _recv() in case of an SSLError

I have a thread which does ws.recv(), sometimes when the connection (wss) is closed a TypeError is thrown saying:

TypeError: argument of type 'int' is not iterable

it happens here:

websocket.py

715 except SSLError as e:
716 if "timed out" in e.args[0]: <--- here
717 raise WebSocketTimeoutException(*e.args)

Mac OSX Compatibility

I had a problem when trying to get this to import on OSX 10.8.5. I would get this error:

import websocket
Traceback (most recent call last):
File "", line 1, in
File "/Users/isospin/Library/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/websocket_client-0.13.0-py2.7.egg/websocket/init.py", line 80, in
(socket.SOL_TCP, socket.TCP_KEEPIDLE, 30),
AttributeError: 'module' object has no attribute 'TCP_KEEPIDLE'

I found a page which notes that osx's python socket module is not necessarily complete:

http://delog.wordpress.com/2013/08/16/handling-tcp-keepalive/

Digging into the websocket init.py revealed these lines:

DEFAULT_SOCKET_OPTION = (
(socket.SOL_TCP, socket.TCP_NODELAY, 1),
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
(socket.SOL_TCP, socket.TCP_KEEPIDLE, 30),
(socket.SOL_TCP, socket.TCP_KEEPINTVL, 10),
(socket.SOL_TCP, socket.TCP_KEEPCNT, 3)
)

Which I then commented to be:

DEFAULT_SOCKET_OPTION = (
(socket.SOL_TCP, socket.TCP_NODELAY, 1),
# (socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
# (socket.SOL_TCP, socket.TCP_KEEPIDLE, 30),
# (socket.SOL_TCP, socket.TCP_KEEPINTVL, 10),
# (socket.SOL_TCP, socket.TCP_KEEPCNT, 3)
)

Now it imports fine. I don't know what consequences this will have.

0.14.1 exception in python3 because struct.pack() returns bytes

(venv-py33-03)21:56:00+nlevitt@Noah-Levitts-MacBook-Pro:~/workspace/umbra$ python
Python 3.3.5 (default, Mar  9 2014, 08:10:50) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import websocket
>>> ws = websocket.WebSocket()
>>> ws.connect("ws://echo.websocket.org/")
>>> ws.send("x")
7
>>> ws.send("x"*127)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/tmp/venv-py33-03/lib/python3.3/site-packages/websocket/__init__.py", line 655, in send
    return self.send_frame(frame)
  File "/tmp/venv-py33-03/lib/python3.3/site-packages/websocket/__init__.py", line 674, in send_frame
    data = frame.format()
  File "/tmp/venv-py33-03/lib/python3.3/site-packages/websocket/__init__.py", line 340, in format
    frame_header += struct.pack("!H", length)
TypeError: Can't convert 'bytes' object to str implicitly

WebSocketApp.run_with_no_err() silently eats all exceptions

Exceptions thrown inside WebSocketApp's callbacks are silently eaten in WebSocketApp.run_with_no_err(). Can you be a bit more specific in what you catch and let other exceptions be passed through Python's normal exception handling mechanism? It's a bit frustrating to find something's quietly not working and have to manually track down what would have been a simple NameError!

Sample code here:
http://pastebin.com/H9hRA67S

disable Nagle algorithm by default

other websocket clients do it: firefox, chrome, etc.
currently there's dict forwarded to do that manually.
I believe it should be on by default.

"Invalid frame type"

We are using websocket.py to communicate with Socket.IO on a server. Socket.IO sends heartbeat messages and we see those OK, here is some log output of what that looks like. The first line is from the logger in websocket.py and the second line comes from our logger in our on_message() handler:

2011-10-27 15:26:55,862 recv frame: '\x00'
2011-10-27 15:26:55,864 ('Websocket message: ', '2::')

However we occasionally see a problem where websocket.py interprets the first character of the message as a separate frame:

2011-10-27 15:27:12,065 recv frame: '\x00'
2011-10-27 15:27:12,065 recv frame: '2'
2011-10-27 15:27:12,066 ('Websocket message: ', '::')
2011-10-27 15:27:12,068 ('Websocket error: ', (WebSocketException('Invalid frame type',),))

I'm not certain if this is a problem in websocket.py or a problem with the data that is being sent to us from the server

Same exception for ws/wss timeout

currently exceptions are generated on timeout:

ws connect: socket.timeout
wss connect: usually socket.timeout, sometimes ssl.SSLError
ws recv: socket.timeout
wss recv: ssl.SSLError

I propose to harmonise exceptions and raise only one kind of Timeout, e.g. WebSocketTimeout.

I volunteer to implement it too.

Trailing slashes

In one app I am developing I am using a URL that ends with a slash. I see that websocket-client removes trailing slashes from URLs.
Maybe this would solve the problem?

--- a/websocket.py
+++ b/websocket.py
@@ -105,7 +105,6 @@ def _parse_url(url):
         raise ValueError("url is invalid")

     scheme, url = url.split(":", 1)
-    url = url.rstrip("/")

     parsed = urlparse(url, scheme="http")
     if parsed.hostname:

I'm not sure whether you've done this for a particular reason, so, I thought it'd be nice to open an issue rather than doing a pull request.

Thanks!

Pedro

Incorrect custom headers order

Hi,
as far as I understand, the WebSocket draft specifies that the first few headers of the request should be: "GET xxx HTTP/1.1", "Upgrade: WebSocket" and "Connection: Upgrade" in this exact order

But if I specify some custom headers in the options of the connections, they are inserted at the top, instead of at the bottom.

This breaks the websocket functionality as the order is no longer respected.

The fix is easy: move headers.extend(options["header"]) at the bottom of the other headers.

Thanks.

Using deprecated `import md5`

The import md5 should be changed to import hashlib, then md5.md5(…) should be changed to hashlib.md5(…). This is compatible with Python 2.5+.

There's something wrong with WebSocketApp closing procedure

run_forever() is blocking, so to close WebSocketApp we close() it from another thread, like in examples/echoapp_client.py.

OK, what we have.
WebSocket.close() sends "close" frame to the server, the server sends "close" frame in response. WebSocket.close() waits for the response but it fails to receive it (as WebSocketApp.run_forever() is the receiver), ignores all errors and continues closing socket.
Meanwhile in another thread WebSocketApp.run_forever() receives incoming "close" frame, echoes it back (second "close" frame from client), breaks the loop and closes the socket again (third time sending "close" frame)... If only WebSocket.close() is still closing, otherwise various exceptions take place.

The result is unpredictable, sometimes there can be two or three 'close' frames from the client (but The application MUST NOT send any more data frames after sending a Close frame), sometimes it throws exceptions all the time

Here is my echoapp_client.py output (Ubuntu, DigitalOcean):

--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: echo.websocket.org
Origin: http://echo.websocket.org
Sec-WebSocket-Key: qIHo0evVRvCDuU+FgPKL1g==
Sec-WebSocket-Version: 13


-----------------------
--- response header ---
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: YZ/1wsCwuqetCeDWOj4duYsS8x0=
Server: Kaazing Gateway
Date: Mon, 27 Jan 2014 16:16:47 GMT
-----------------------
send: '\x81\x87\x1a\xd8XmR\xbd4\x01u\xf8h'
Hello 0
send: '\x81\x87U\x1a\x9d\xf2\x1d\x7f\xf1\x9e::\xac'
Hello 1
send: '\x81\x87\xc5[\xd9&\x8d>\xb5J\xaa{\xeb'
Hello 2
send: '\x88\x82\xf9"[0\xfa\xca'
send: '\x88\x82\xff\x16%0\xfc\xfe'
send: '\x88\x82\x03\xb4_u\x00\\'
### closed ###

echoapp_client.py output (Windows 7, VirtualBox VM):

--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: echo.websocket.org
Origin: http://echo.websocket.org
Sec-WebSocket-Key: 1VA8DDiJTZiR8fTzM++mGw==
Sec-WebSocket-Version: 13


-----------------------
--- response header ---
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Sec-WebSocket-Accept: MOe1PlriYP5DbBObbeck9jWN5no=
Server: Kaazing Gateway
Date: Mon, 27 Jan 2014 16:23:12 GMT
-----------------------
send: '\x81\x873\xa7\xd6\xcd{\xc2\xba\xa1\\\x87\xe6'
Hello 0
send: '\x81\x87\x85\x8a=\xff\xcd\xefQ\x93\xea\xaa\x0c'
Hello 1
send: '\x81\x87\xb3\xf6\xb4\xe1\xfb\x93\xd8\x8d\xdc\xd6\x86'
Hello 2
send: '\x88\x82\xbe?x\xf0\xbd\xd7'
sTend: '\x88\x82y\xe9\x17\x99z\x01'
hread terminating...[Errno 9] Bad file descriptor
### closed ###

WebSocketApp closing must be more graceful.

Dual-license

Hi, would you consider changing license to Apache License v 2.0?
or perhaps dual license LGPL / Apache?

lgpl makes it a bit hard to redistribute via py2app/py2exe/etc.

Won't install on Python 2.6

I'm getting an error trying to instatll on 2.6:

 Reading http://pypi.python.org/simple/websocket-client/
[12:11:51][Step 1/1] Best match: websocket-client 0.14.0
[12:11:51][Step 1/1] Downloading https://pypi.python.org/packages/source/w/websocket-client/websocket-client-0.14.0.tar.gz#md5=3de864134e57f132851c9a961afc1fab
[12:11:51][Step 1/1] Processing websocket-client-0.14.0.tar.gz
[12:11:52][Step 1/1] Writing /tmp/easy_install-7eAK3_/websocket-client-0.14.0/setup.cfg
[12:11:52][Step 1/1] Running websocket-client-0.14.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-7eAK3_/websocket-client-0.14.0/egg-dist-tmp-80wceC
[12:11:52][Step 1/1] Traceback (most recent call last):
[12:11:52][Step 1/1]   File "/usr/bin/easy_install", line 9, in <module>
[12:11:52][Step 1/1]     load_entry_point('distribute==0.6.49', 'console_scripts', 'easy_install')()
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/command/easy_install.py", line 1973, in main
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/command/easy_install.py", line 1954, in with_ei_usage
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/command/easy_install.py", line 1977, in <lambda>
[12:11:52][Step 1/1]   File "/usr/lib/python2.6/distutils/core.py", line 152, in setup
[12:11:52][Step 1/1]     dist.run_commands()
[12:11:52][Step 1/1]   File "/usr/lib/python2.6/distutils/dist.py", line 975, in run_commands
[12:11:52][Step 1/1]     self.run_command(cmd)
[12:11:52][Step 1/1]   File "/usr/lib/python2.6/distutils/dist.py", line 995, in run_command
[12:11:52][Step 1/1]     cmd_obj.run()
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/command/easy_install.py", line 360, in run
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/command/easy_install.py", line 604, in easy_install
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/command/easy_install.py", line 634, in install_item
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/command/easy_install.py", line 829, in install_eggs
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/command/easy_install.py", line 1109, in build_and_install
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/command/easy_install.py", line 1095, in run_setup
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/sandbox.py", line 33, in run_setup
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/sandbox.py", line 81, in run
[12:11:52][Step 1/1]   File "build/bdist.linux-armv7l/egg/setuptools/sandbox.py", line 35, in <lambda>
[12:11:52][Step 1/1]   File "setup.py", line 7, in <module>
[12:11:52][Step 1/1] AttributeError: 'tuple' object has no attribute 'major'

SSL error in 0.13.0v

OS X 10.9.2 (Mavericks) on "wss://eample.com/v1/"

File "/usr/local/opt/pyenv/versions/xxx/lib/python2.7/site-packages/websocket/__init__.py", line 214, in create_connection
    websock.connect(url, **options)
  File "/usr/local/opt/pyenv/versions/xxx/lib/python2.7/site-packages/websocket/__init__.py", line 470, in connect
    self.sock = ssl.wrap_socket(self.sock, **sslopt)
  File "/usr/local/opt/pyenv/versions/xxx/lib/python2.7/site-packages/gevent/ssl.py", line 383, in wrap_socket
    ciphers=ciphers)
  File "/usr/local/opt/pyenv/versions/xxx/lib/python2.7/site-packages/gevent/ssl.py", line 94, in __init__
    self.do_handshake()
  File "/usr/local/opt/pyenv/versions/xxx/lib/python2.7/site-packages/gevent/ssl.py", line 305, in do_handshake
    return self._sslobj.do_handshake()
ssl.SSLError: [Errno 1] _ssl.c:507: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

In 0.12.0 Work normal

Controlling fragmentation

I use this library to test various server and client implementations in embedded environments and I found that I couldn't send fragments using the "low-level API" without constructing the ABNF frame myself, etc.

Do you think the WebSocket class can benefit from some sort of send_fragment(self, payload, opcode, final) method? Or do you think there's a better approach to this? Ready to submit a patch.

Thanks!

partial messages

If you're blocked on a recv() call and the connection is closed, what will be returned? None, or a partial message?

WSS and SSL

When I launch my websocket app on a WSS url, I have the following warning in your lib:

websocket.py:201: DeprecationWarning: socket.ssl() is deprecated.
Use ssl.wrap_socket() instead.
self.ssl = socket.ssl(sock)

and sometimes (with SSL only) the connection ends with the following error:
[Errno 8] _ssl.c:1331: EOF occurred in violation of protocol

That would be nice if you could use ssl.wrap_socket() :)
Thanks for all

Regards,

RFC 6455 support?

I've got an app written using the ws package for node and I'd like to use this package to wire in a simple data-logger. However, the package doesn't quite work if I run my script from the command-line - I get errors like this (and the data is scrambled):

 Traceback (most recent call last):
  File "/Users/bonka/wstest/monitor.py", line 5, in <module>
    result = ws.recv()
  File "/Users/bonka/wstest/lib/python2.7/site-packages/websocket.py", line 518, in recv
    opcode, data = self.recv_data()
  File "/Users/bonka/wstest/lib/python2.7/site-packages/websocket.py", line 532, in recv_data
    raise WebSocketException("Not a valid frame %s" % frame)
websocket.WebSocketException: Not a valid frame None

If, however, I cut and paste the code into an interactive python session, it works without error ...

The code:

from websocket import create_connection

ws = create_connection("ws://localhost/monitor")
while True:
    result = ws.recv()
    print result

egg on pypi is broken

When I try to install the package from pypi I get an error

error: README.rst: No such file or directory
An error occurred when trying to install websocket-client 0.5.0. Look above this message for any errors that were output by easy_install.

You refer to README.rst in setup.py, but this file is not in the tarball, I have had the same problems before and solved them by using a Manifest.in file in the package.

data = self.sock.recv() causes hang

The line here:

            while self.keep_running:
                data = self.sock.recv()
                # Doesn't get this far before hang
                if data is None:
                    break
                self._callback(self.on_message, data)

is causing an infinite hang. I've narrowed it down to data = self.sock.recv(). A lack of timeout or data limit args seems to be the direct cause.

Clarify protocols supported

I'm trying to get websocket-client to speak to a cyclone WebsocketHandler. See: https://github.com/fiorix/cyclone/blob/master/demos/websocket/websocket.tac

I get a bad handshake error (below). I need to know the protocols you support to work out if this should be happening or not.

-- request header ---
GET /enginebus/demo1 HTTP/1.1
Upgrade: WebSocket
Connection: Upgrade
Host: 127.0.0.1:8888
Origin: 127.0.0.1:8888
Sec-WebSocket-Key1: 28D|s4NI8c H6`4864n6 XM
Sec-WebSocket-Key2: 3 u 4 g6 #6 8b9q1980 M

?=@?(

--- response header ---
HTTP/1.1 101 Web Socket Protocol Handshake
Upgrade: WebSocket
Connection: Upgrade
Server: CycloneServer/0.4
Sec-WebSocket-Origin: 127.0.0.1:8888

Sec-WebSocket-Location: ws://127.0.0.1:8888/enginebus/demo1

--- challenge response result ---

'\x00c\xa1Yu]K"\x89\x82\xb2\xfc\xbf1\xe1u'

Sending 'Hello, World'...
send: '\x00Hello, World\xff'
Sent
Reeiving...
recv frame: '\r'
Traceback (most recent call last):
File "engine/runtime.py", line 29, in
result = ws.recv()
File "/Users/james/Documents/virtualenvs/backplay/lib/python2.7/site-packages/websocket.py", line 370, in recv
raise WebSocketException("Invalid frame type")
websocket.WebSocketException: Invalid frame type

Payload length encoding bug

Line # 253: LENGTH_7 = 0x7d

The value should be 0x7e, coz you are using it with: if length < ABNF.LENGTH_7:

How to re-establish the WebSocket Connection to the server: Please Advice

Hello liris,

I greatly appreciate your work and this is working great in happy scenarios !! Great

Since I need to cover few more cases of network failure/re-connection:
When WebSocket Client loses network connection to the server. What Exception websocket.py throws and what is the best way for me to re-establish the connection back the server.
I am using WebSocketApp class and On_message, On_Error, On_Close and On-Open mentods.
Currently, Websocket does not seem to throw any exception immediately. It tries for 15-20 iteration and goes calls on_error() function. (Please correct me if my understanding is wrong)
Given this: What is the best way for me to re-connect with the server. Any sample code/documentation is greatly appreciated

Please advice,
High Regards

Srini

Passing a TCP_NODELAY flag to the websocket constructor

Not really an issue, more a feature request. We need to avoid Nagle's algorithm, because when combined to delayed acks, it adds considerable delays.
See http://en.wikipedia.org/wiki/Nagle%27s_algorithm#Algorithm

I'm suggesting adding something along these few lines to the WebSocket constructor:

sock = socket.socket()
if tcp_nodelay:
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.io_sock = self.sock = socket.socket()

Thanks!

clarification re on_message receiving bytes in websocket-client-py3 0.13

websocket-client-py3 0.12

>>> import websocket
>>> ws = websocket.WebSocketApp("ws://echo.websocket.org/", on_open=lambda ws: ws.send("hélló"), on_message=lambda ws, message: print('received {}'.format(message)))
>>> ws.run_forever()
received hélló

websocket-client-py3 0.13

>>> import websocket
>>> ws = websocket.WebSocketApp("ws://echo.websocket.org/", on_open=lambda ws: ws.send("hélló"), on_message=lambda ws, message: print('received {}'.format(message)))
>>> ws.run_forever()
received b'h\xc3\xa9ll\xc3\xb3'

I think this is probably a good change. It does break backward compatibility though. And I don't see it mentioned in the ChangeLog section of the readme. It's also not at all obvious to me from the commit log when it changed.

So is this intentional? If so it would probably be good to document it explicitly.

Timing out leaves websocket library in bad state

Consider a situation where a really big WebSocket message coming over the wire, the network connection slow, and the socket timeout has be set relatively tightly. Accumulating the message frame takes multiple calls to socket.recv() any of which may trigger timeout. Suppose that one of them (and not the last one) times out causing either socket.timeout or ssl.SSLError that the calling code handles gracefully. Now the next call to websocket.WebSocket.recv() will start reading the new frame from a position in the middle of the previous frame resulting in totally broken nonsense frames from thereon.

I think the library should guard against this situation by continuing to complete the previous partial frame on the next call to websocket.WebSocket.recv() (or its friends).

Timing out a websocket app

I'm trying to open a websocket and receive a set of data. However, the websocketapp does not appear to expose a way to close the socket once the socket has not received data for a period of time.

What is "sys_exc_info()"?

I'm trying to run websocket-client under Python3 and I get this error:

websocketclient/websocket.py", line 816, in _callback
_, _, tb = sys_exc_info()
NameError: global name 'sys_exc_info' is not defined

What are you trying to accomplish here and how can it be fixed?

Not able to install the new zip file : Please help - urgent

Hi,

As per your advice for for issue 64, I wanted to send you the log file from the newest install.
After the zip file when I run python setup.py install. I donot see websocket.py file installed in the directory. Please find the attached screen shots
websocket
Please advice: If I am doing anything silly. Earlier this was not the case.

Thanks and Regards,

Look forward to your reply !

BRE

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.