Home » Python

Implementation of WebSocket using Socket-IO in Python

Python WebSocket Implementation: In this tutorial, we are going to learn how to implement WebSocket using Socket-IO in Python?
Submitted by Sapna Deraje Radhakrishna, on September 22, 2019

Python WebSocket using Socket-IO

WebSocket protocol is widely supported standard to implement real-time applications. It helps in transforming to cross-platform in a real-time world between server and client. Websockets has an advantage over an HTTP connection that it provides full-duplex communication. Often, WebSockets are confused with socket, the difference between WebSockets and sockets are as follows:

WebSocket Socket.IO
Protocol which is established over the TCP connection. Library to work with WebSocket.
Provides full duplex communications over TCP. Provides event based communication between server and client.
Doesn't support proxies and load balancers. Connection can be established in the presence of proxies and load balancers.
No broadcasting. Supports broadcasting.

Among the many libraries available, is the python-socketio for implementing the WebSocket functionality in python.

Installation of the libraries in the virtual environment

  • Create a virtual environment
    -bash-4.2$ python3 -m venv venv
  • Source (or activate) the virtual environment
    -bash-4.2$ source venv/bin/activate
  • Install the required library using pip
    (venv) -bash-4.2$ pip install python-socketio
    ...
    Successfully installed python-engineio-3.9.3 python-socketio-4.3.1
    
    (venv) -bash-4.2$ pip install aiohttp
    ...
    Successfully installed aiohttp-3.6.1 async-timeout-3.0.1 idna-ssl-1.1.0 
    multidict-4.5.2 typing-extensions-3.7.4 yarl-1.3.0
    

Example server code ( socket_io_server.py)

from aiohttp import web
import socketio
import os

# create a new aysnc socket io server
socket_io = socketio.AsyncServer()

#create a new Aiohttp web application
web_app = web.Application()

#bind the socket.io server to the web application instance
socket_io.attach(web_app)

#define endpoints 
async def index(request):
    dirname = os.path.dirname(__file__)
    filename = os.path.join(dirname, '/templates/index.html')
    with open(filename) as file_obj:
        return web.Response(text = file_obj.read(), content_type='text/html')


@socket_io.on('message')
async def print_message(id, message):
    print("socket id is {}".format(id))
    print(message)
    #enabling two-way communication
    await socket_io.emit('message', "you said {}".format(message))


#bind the aiohttp endpoint to the web_application
web_app.router.add_get('/',index)

#start the server
if __name__ == '__main__':
    web.run_app(web_app)

Example client code (index.html)

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Include Help Socket IO</title>
  </head>
  <body>
    <button onClick="sendToServer()">Hit Me</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
    <script>
	<!-change the host if sending the message outside localhost ->
      const socket = io("http://localhost:8080");

      function sendToServer () {
        socket.emit("message", "HELLO INCLUDE HELP");
      }
      <!-to view this message hit f12 and select on console tab ->
      socket.on("message", function(data) {
  			console.log(data)
	  });

    </script>
  </body>
</html>

Execute the server code (python3 socket_io_server.py)

    (venv) -bash-4.2$ python3 socket_io_server.py
    ======== Running on http://0.0.0.0:8080 ========
    (Press CTRL+C to quit)

In the brower, open: http://localhost:8080

websocket implementation in python

Server logs

    socket id is a5c3c73715fc4e9380477daf56f26fe2
    HELLO INCLUDE HELP

And in Client side ( brower)

websocket implementation in python output






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.