import asyncio
import websockets
async def receive_message(websocket):
async for message in websocket:
print(f"Received: {message}")
async def send_message(websocket):
while True:
message = "Server message"
await websocket.send(message)
await asyncio.sleep(5)
async def handle_connection(websocket, path):
print(f"Client connected.")
receive_task = asyncio.create_task(receive_message(websocket))
send_task = asyncio.create_task(send_message(websocket))
await asyncio.gather(receive_task, send_task)
async def start_server():
server = await websockets.serve(handle_connection, 'localhost', 8888)
print(f"Server started on port 8888.")
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(start_server())
import asyncio
import websockets
connected_clients = set()
async def receive_message(websocket):
async for message in websocket:
print(f"Received: {message}")
async def send_message(websocket):
while True:
message = "Server message"
await websocket.send(message)
await asyncio.sleep(5)
async def disconnect_server(websocket):
connected_clients.remove(websocket)
await websocket.close()
print("Client disconnected.")
async def handle_connection(websocket, path):
print(f"Client connected.")
connected_clients.add(websocket)
receive_task = asyncio.create_task(receive_message(websocket))
send_task = asyncio.create_task(send_message(websocket))
try:
await asyncio.gather(receive_task, send_task)
except websockets.exceptions.ConnectionClosedError:
await disconnect_server(websocket)
async def start_server():
server = await websockets.serve(handle_connection, 'localhost', 8888)
print(f"Server started on port 8888.")
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(start_server())
import asyncio
import websockets
async def receive_message(websocket):
async for message in websocket:
print(f"Received from server: {message}")
async def send_message(websocket):
while True:
message = input("Enter a message to send: ")
await websocket.send(message)
async def connect_to_server():
async with websockets.connect('ws://localhost:8888') as websocket:
print("Connected to server.")
receive_task = asyncio.create_task(receive_message(websocket))
send_task = asyncio.create_task(send_message(websocket))
await asyncio.gather(receive_task, send_task)
if __name__ == "__main__":
asyncio.run(connect_to_server())