import asyncio
import websockets
async def handle_connection(websocket, path):
client_ip, client_port = websocket.remote_address
print(f"Client connected from {client_ip}:{client_port}")
try:
while True:
message = await websocket.recv()
print(f"Received message from {client_ip}:{client_port}: {message}")
# Include the client's port in the response
response = f"Server received on port {client_port}: {message}"
await websocket.send(response)
print(f"Sent response to {client_ip}:{client_port}: {response}")
except websockets.exceptions.ConnectionClosed:
print(f"Client {client_ip}:{client_port} disconnected")
start_server = websockets.serve(handle_connection, "0.0.0.0", 8080)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
Client
import asyncio
import websockets
import time
async def send_message():
#uri = "ws://localhost:3000"
uri = "ws://localhost:8080"
async with websockets.connect(uri) as websocket:
# Send a message to the server
message = "Hello, WebSocket Server!"
await websocket.send(message)
print(f"Sent message: {message}")
# Receive and print the server's response
response = await websocket.recv()
print(f"Received response: {response}")
# Run the client
while True:
asyncio.get_event_loop().run_until_complete(send_message())
time.sleep(1)
Server
Client