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
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
Server logs
socket id is a5c3c73715fc4e9380477daf56f26fe2
HELLO INCLUDE HELP
And in Client side ( brower)