WebSocket Client for Python

Source: Internet
Author: User
Tags cert verification

Project description

Websocket-client module is websocket client for Python. This provide the low level APIs for WebSocket. All APIs is the synchronous functions.

Websocket-client supports only hybi-13.

License
  • Lgpl
Installation

This module was tested on Python 2.7 and Python 3.4+.

Type "python setup.py Install" or "Pip install websocket-client" to install.

caution!

From v0.16.0, we can install by ' pip install Websocket-client ' for Python 3.

This module depends on

  • Six
  • Backports.ssl_match_hostname for Python 2.x
Performance

"Send" method is too slow on pure python. If you want to get better performace, please install NumPy or wsaccel. You can get the best performance from NumPy.

How about Python 3

Now, we support Python 3 on single source code from version 0.14.0. Thanks, @battlemidget and @ralphbean.

HTTP Proxy

Support WebSocket access via HTTP proxy. The proxy server must allow "CONNECT" method to WebSocket port. Default squid setting is "allowed-CONNECT only HTTPS PORT".

Current implementation of Websocket-client is using "CONNECT" method via proxy.

Example

WebSocketwebsocket.  WebSocket()ws.  Connect("Ws://example.com/websocket"http_proxy_host="Proxy_host_name"http_proxy_ Port=3128)               
exampleslong-lived Connection

This example is similar-to-WebSocket code looks in browsers using JavaScript.

ImportWebSocketTry:    ImportThreadexceptImporterror:Import_thread as ThreadImport Timedefon_message (WS, message):Print(message)defon_error (WS, error):Print(Error)defon_close (WS):Print("# # # closed # #")defOn_open (WS):defRun (*args): forIinchRange (3): Time.sleep (1) Ws.send ("Hello%d"%i) Time.sleep (1) Ws.close ()Print("thread terminating ...") Thread.start_new_thread (Run, ())if __name__=="__main__": Websocket.enabletrace (True) WS= WebSocket. Websocketapp ("ws://echo.websocket.org/", On_message=On_message, On_error=On_error, On_close=on_close) Ws.on_open=on_open ws.run_forever ()
Short-lived one-off send-receive

This is if you want to communicate a short message and disconnect immediately when done.

 fromWebSocketImportCREATE_CONNECTIONWS= Create_connection ("ws://echo.websocket.org/")Print("sending ' Hello, World ' ...") Ws.send ("Hello, World")Print("Sent")Print("receiving ...") Result=ws.recv ()Print("Received '%s '"%result) ws.close ()

If you want to customize socket options, set sockopt.

sockopt Example

 from Import  = create_connection ("ws://echo.websocket.org/",                        sockopt= ( Socket. IPPROTO_TCP, Socket. Tcp_nodelay),))
More Advanced:custom class

You can also write your own class for the connection, if you want to handle the nitty-gritty details yourself.

ImportSocket fromWebSocketImportcreate_connection, WebSocketclassMywebsocket (WebSocket):defRecv_frame (self): frame=super (). Recv_frame ()Print('yay! I got this frame:', frame)returnframews= Create_connection ("ws://echo.websocket.org/", Sockopt= (socket. IPPROTO_TCP, Socket. Tcp_nodelay, 1),), Class_=mywebsocket)

Faqhow To disable SSL cert verification?

Please set sslopt to {"Cert_reqs": SSL. Cert_none}.

Websocketapp sample

WS = WebSocket. Websocketapp ("wss://echo.websocket.org") ws.run_forever (sslopt={" Cert_reqs ": SSL. Cert_none})

Create_connection sample

WS = Websocket.create_connection ("wss://echo.websocket.org",  sslopt={ " Cert_reqs ": SSL. Cert_none})

WebSocket sample

WS = WebSocket. WebSocket (sslopt={"cert_reqs": SSL. Cert_none}) Ws.connect ("wss://echo.websocket.org")
How to disable hostname verification.

Please set sslopt to {"Check_hostname": False}. (Since v0.18.0)

Websocketapp sample

WS = WebSocket. Websocketapp ("wss://echo.websocket.org") ws.run_forever (sslopt={" Check_hostname ": False})

Create_connection sample

WS = Websocket.create_connection ("wss://echo.websocket.org",  sslopt={ " Check_hostname ": False})

WebSocket sample

WS = WebSocket. WebSocket (sslopt={"check_hostname": False}) Ws.connect ("wss:// echo.websocket.org")
How to enable SNI?

SNI support is available for Python 2.7.9+ and 3.2+. It'll be enabled automatically whenever possible.

Sub protocols.

The server needs to support sub protocols, please set the Subprotocol as this.

Subprotocol sample

WS = Websocket.create_connection ("ws://example.com/websocket", subprotocols=["  binary""base64"])
wsdump.py

Wsdump.py is a simple WebSocket test (Debug) tool.

Sample for echo.websocket.org:

$ wsdump.py Ws://echo.websocket.org/press Ctrl + C to quit> hello, websocket< Hello, websocket> how is you?< Ho W is you?
Usage

Usage

wsdump.py [-h] [-V [VERBOSE]] Ws_url

WebSocket Simple Dump Tool

Positional arguments:
Ws_url websocket URL. Ex. ws://echo.websocket.org/
Optional arguments:
-h, --help Show this help message and exit
Websocketapp
-v VERBOSE, --verbose VERBOSE
Set verbose mode. If set to 1, show opcode. If set to 2, enable to trace WebSocket module

Example

$ wsdump.py ws://echo.websocket.org/$ wsdump.py ws://echo.websocket.org/-v$ wsdump.py ws://echo.websocket.org/-vv

WebSocket Client for Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.