Sure! Here’s an example code for a simple WebSocket-based instant messaging system using Python on both client and server:
Server
import asyncio
import websockets
connected = set()
async def handle_client(websocket, path):
# register current websocket as connected to the server
connected.add(websocket)
try:
async for message in websocket:
# when a message is received, broadcast it to all connected clients
for conn in connected:
if conn != websocket:
await conn.send(message)
finally:
# unregister the websocket from the connected set when it disconnects
connected.remove(websocket)
async def start_server():
async with websockets.serve(handle_client, "localhost", 8765):
await asyncio.Future() # keep the server running indefinitely
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(start_server())
This code creates a WebSocket server that listens on port 8765. When a client connects, it registers the client’s WebSocket connection in a set of connected clients. When a client sends a message, the server broadcasts it to all connected clients (except for the sender). Finally, the server runs indefinitely until a future object is completed.
Client
import asyncio
import websockets
async def receive_messages():
async with websockets.connect('ws://localhost:8765') as websocket:
while True:
# wait for incoming messages and print them to the console
message = await websocket.recv()
print('> Received message: %s' % message)
async def send_message():
async with websockets.connect('ws://localhost:8765') as websocket:
while True:
# read user input and send it to the server
message = input('> Send message: ')
await websocket.send(message)
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(asyncio.gather(
receive_messages(),
send_message()))
This code creates a WebSocket client that connects to the server on localhost:8765. It then runs two coroutines, one for receiving messages and one for sending messages. The receive_messages
coroutine listens for incoming messages from the server and prints them to the console. The send_message
coroutine reads user input and sends it to the server. Both coroutines run indefinitely until the program is terminated.
That’s it! With these two code snippets, you should be able to run a simple WebSocket-based instant messaging system in Python.