Home » Python

What is WebSocket and how to use it in Python?

WebSockets in Python: Here, we are going to learn what is WebSocket and how to use it in Python?
Submitted by Sapna Deraje Radhakrishna, on September 17, 2019

What is WebSocket?

WebSocket is a communications protocol which provides a full-duplex communication channel over a single TCP connection. WebSocket protocol is standardized by the IETF as RFC 6455.

WebSocket and HTTP, both distinct and are located in layer 7 of the OSI model and depend on TCP at layer 4. RFC 6455 states that "WebSocket is designed to work over HTTP ports 80 and 443 as well as to support HTTP proxies and intermediaries", making it compatible with HTTP protocol. WebSocket handshake uses the HTTP Upgrade header to change from the HTTP to WebSocket protocol.

WebSocket protocol enables interaction between a web browser or any client application and a web server, facilitating the real-time data transfer from and to the server.

Most of the newer version of browsers such as Google Chrome, IE, Firefox, Safari, and Opera support the WebSocket protocol.

WebSocket in Python

Python WebSocket implementations

There are multiple projects which provide either the implementations of web socket or provide with examples for the same.

  1. Autobahn – uses Twisted and Asyncio to create the server-side components, while AutobahnJS provides client-side.
  2. Flask – SocketIO is a flask extension.
  3. WebSocket –client provides low-level APIs for web sockets and works on both Python2 and Python3.
  4. Django Channels is built on top of WebSockets and useful in and easy to integrate the Django applications.

Python Example of application using WebSocket-client library

The WebSocket client library is used to connect to a WebSocket server,

Prerequisites:

Install WebSocket client using pip within the virtual environment,

  • Create a virtual environment
    python3 -m venv /path/to/virtual/environment
    >> python3 -m venv venv
  • Source the virtual environment
    >> source venv/bin/activate
  • Install the websocket-client using pip
    >> (venv) pip3 install websocket_client
Collecting websocket_client==0.56.0 (from -r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/29/19/44753eab1fdb50770ac69605527e8859468f3c0fd7dc5a76dd9c4dbd7906/websocket_client-0.56.0-py2.py3-none-any.whl (200kB)
    100% |          | 204kB 2.7MB/s 
Collecting six (from websocket_client==0.56.0->-r requirements.txt (line 1))
  Downloading https://files.pythonhosted.org/packages/73/fb/00a976f728d0d1fecfe898238ce23f502a721c0ac0ecfedb80e0d88c64e9/six-1.12.0-py2.py3-none-any.whl
Installing collected packages: six, websocket-client
Successfully installed six-1.12.0 websocket-client-0.56.0

The below example is compatible with python3, and tries to connect to a web socket server.

Example 1: Short lived connection

from websocket import create_connection

def short_lived_connection():
    ws = create_connection("ws://localhost:4040/")
    print("Sending 'Hello Server'...")
    ws.send("Hello, Server")
    print("Sent")
    print("Receiving...")
    result =  ws.recv()
    print("Received '%s'" % result)
    ws.close()

if __name__ == '__main__':
    short_lived_connection()

Output

Sending 'Hello, World'...
Sent
Receiving...
Received 'hello world'

The short lived connection, is useful when the client doesn't have to keep the session alive for ever and is used to send the data only at a given instant.

Example 2: Long Lived connection

import websocket

def on_message(ws, message):
    '''
        This method is invoked when ever the client
        receives any message from server
    '''
    print("received message as {}".format(message))
    ws.send("hello again")
    print("sending 'hello again'")

def on_error(ws, error):
    '''
        This method is invoked when there is an error in connectivity
    '''
    print("received error as {}".format(error))

def on_close(ws):
    '''
        This method is invoked when the connection between the 
        client and server is closed
    '''
    print("Connection closed")

def on_open(ws):
    '''
        This method is invoked as soon as the connection between 
		client and server is opened and only for the first time
    '''
    ws.send("hello there")
    print("sent message on open")


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://localhost:4040/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

Output

--- request header ---
GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: localhost:4040
Origin: http://localhost:4040
Sec-WebSocket-Key: q0+vBfXgMvGGywjDaHZWiw==
Sec-WebSocket-Version: 13


-----------------------
--- response header ---
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: /YqMq5iNGOMjtELPGCZsnozMSlw=
Date: Sun, 15 Sep 2019 23:34:04 GMT
Server: Python/3.7 websockets/8.0.2
-----------------------
send: b'\x81\x8b\xcb\xeaY.\xa3\x8f5B\xa4\xca-F\xae\x98<'
sent message on open
send: b'\x81\x8b\x00\xe9Y{h\x8c5\x17o\xc98\x1ca\x807'
received message as hello world
sending 'hello again'
received message as hello world
send: b'\x81\x8b\x9f\xa3\xb2\xd8\xf7\xc6\xde\xb4\xf0\x83\xd3\xbf\xfe\xca\xdc'sending 'hello again'

received message as hello world
send: b'\x81\x8b\xfd\x0c\xd0\xb0\x95i\xbc\xdc\x92,\xb1\xd7\x9ce\xbe'
sending 'hello again'


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.