How to build a WebSocket server in Python?
There are different types of ways a computer can communicate with each other. The most common methods of communication amongst them are HTTP and WebSocket. In this article, we will venture deep into computer networks and get to know more about Websocket and also create a WebSocket server in Python at the end.
What is a Protocol?
Computers are very bad at communicating with other computers. So, they have to follow a certain set of rules to work among themselves and get going. These set of rules are protocols.
Protocols give structure and proper logic to the processes sent or received by a computer. Through the use of protocols, computers connect and share data across the internet. Several types of protocols connect to the internet, each having different use cases. One of them is HTTP, also known as HyperText Transfer Protocol.
What is HTTP?
HyperText Transfer Protocol or HTTP is a protocol that acts as the base foundation of the Web technology we use today. It is a server-client protocol using special methods such as request, the message sent from client to server, and response, the message/data sent by the server to the client as a response to the request.
When the client uses the browser to access any website, the client sends a GET request to the server informing that it is ready to receive the necessary data. Then the server sends the response containing the resources of the website. The browser uses these resources to construct the frontend of the website. The user interacts with the frontend to further browse and access more data easily. Whenever the user submits any form, the browser sends a POST request to the server which contains the data filled through the form. Even though the GET and POST methods are enough to run the Website, there are many more methods available like PUT, PATCH, etc which perform complex features with great ease.
To know more about HTTP in-depth, visit this article by Mozilla.
What is a Socket?
If two computers/programs are connected through the internet, then in this two-way communication channel, each endpoint is called a socket. Each socket inside a computer has a unique socket address. The socket address contains the IP address of the machine and the port number on which the socket is open for connections.
For a two-way connection in applications via sockets, first, the server creates a socket and attaches itself to it. The servers use these sockets to listen to any incoming connection requests by the clients. The client creates a socket and uses this socket to attempt to connect to the server socket. As soon as the connection is established, communication between the two computers can take place along with data transfer.
To know more about sockets, refer to this article.
What are Websockets?
Websockets are bi-directional communication channels. Therefore when a client connects to the server via a WebSocket, the client and the server will interact with each other multiple times in a single connection. Websockets have a duplex connection protocol. Basically, the connection will stay alive as long as both the members of the channel (the client and the server) are still connected. If anyone drops off the connection, the whole connection is broken.
To know more about sockets, refer to this article.
Websocket vs HTTP
Websocket | HTTP |
---|---|
The websocket is bidrectional. | HTTP is a unidirectional communication channel. |
Websocket keeps the connection alive as long as both the ends are connected. | HTTP connection breaks as soon as the response is given by the server to the client’s request. |
Real-time applications use websockets as the data updates frequently | Simple web applications use HTTP whose data remains the same for a longer time. |
Applications that require the client to stay connected and to keep getting the inputs, use websockets | Applications that do not require frequent updates in data and inputs from the user use HTTP. |
Advantages of WebSockets
- Moreover in terms of speed, websockets are faster than HTTP.
- Data on the website updates very frequently through a continuous stream of data coming from either side.
- Furthermore the connection between the client and the server stays alive for as long as required.
Limitations of WebSockets
- There is no need to use websockets if there is no need for transferring a continuous stream of data.
- Communication through websockets only is not inherently scalable.
Building a Chat App using WebSockets
Firstly, creating a server which echoes “client connected” whenever a client is connected.
import websockets
import asyncio
# Server data
PORT = 7890
print("Server listening on Port " + str(PORT))
# A set of connected ws clients
connected = set()
# The main behavior function for this server
async def echo(websocket, path):
print("A client just connected")
# Store a copy of the connected client
connected.add(websocket)
# Handle incoming messages
try:
async for message in websocket:
print("Received message from client: " + message)
# Send a response to all connected clients except sender
for conn in connected:
if conn != websocket:
await conn.send("Someone said: " + message)
# Handle disconnecting clients
except websockets.exceptions.ConnectionClosed as e:
print("A client just disconnected")
finally:
connected.remove(websocket)
# Start the server
start_server = websockets.serve(echo, "localhost", PORT)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Code language: Python (python)
Then creating the client which connects with the server:
import websockets
import asyncio
# The main function that will handle connection and communication
# with the server
async def listen():
url = "ws://127.0.0.1:7890"
# Connect to the server
async with websockets.connect(url) as ws:
# Send a greeting message
await ws.send("Hello Server!")
# Stay alive forever, listening to incoming msgs
while True:
msg = await ws.recv()
print(msg)
# Start the connection
asyncio.get_event_loop().run_until_complete(listen())
Code language: Python (python)
Conclusion
The websocket use depends on the type of application in development. Web applications like Games or real-time analytics, etc, use websockets to keep a continuous flow of data otherwise normal HTTP and its methods are enough for a project to work throughout the internet.
Sharing is caring
Did you like what Aman Ahmed Siddiqui wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: