I would like to create a WebSocket communication between my personal laptop and a server. I have created the client.py
and server.py
, and they look as follows:
Firstly, the server:
import asyncio
import websockets
async def handle_client(websocket):
try:
async for message in websocket:
if isinstance(message, bytes): # binary frame (image)
print(f"Received image of {len(message)} bytes")
# (optional) save to disk for testing
with open("received.jpg", "wb") as f:
f.write(message)
# Generate a response (in real case: run model inference here)
response = "Server: image received and processed!"
await websocket.send(response)
else:
# Fallback if a client sends text
print("Received text:", message)
await websocket.send("Server: got your text!")
except websockets.exceptions.ConnectionClosed:
print("Client disconnected")
async def main():
server = await websockets.serve(handle_client, "0.0.0.0", 12348)
print("Server running...")
await server.wait_closed()
if __name__ == "__main__":
asyncio.run(main())
and then the client:
import cv2
import asyncio
import websockets
async def send_image():
frame = cv2.imread("temp.jpg") # replace with your file path
# Encode as JPEG
success, jpg = cv2.imencode(".jpg", frame)
if not success:
print("Encoding failed")
return
data = jpg.tobytes()
# Connect and send
async with websockets.connect("ws://xxx.xxx.xx.xxx:12348") as websocket: # here I add the IP of the server found after running ipconfig
await websocket.send(data) # send as binary
print(f"Sent image ({len(data)} bytes)")
# Wait for server reply
response = await websocket.recv()
print("Server replied:", response)
if __name__ == "__main__":
asyncio.run(send_image())
When I am running both server
and the client
, the programs are running, but I get no reaction from the server. Is there something I need to do differently? Is there something wrong with my code?
I am actually getting a timeout:
raise TimeoutError("timed out during opening handshake") from exc TimeoutError: timed out during opening handshake
Edit: It seems that the issue lies with the following line:
async with websockets.connect("ws://xxx.xxx.xx.xxx:12348") as websocket:
It might be that I am doing something wrong when I am trying to connect to my server using server's IP. Is that the correct thing to do?
1 Answer 1
You are getting the timeout because the client cannot reach the server. The handshake never happens.
- If both server and client are on the same machine, use
ws://localhost:12348
- If they are on different devices use the local network ip address of the server like
ws://192.168.x.x:12348
Make sure both are on the same wifi network. Check that the firewall on the server allows inbound connections on port 12348. On Windows, you can do that with netsh advfirewall firewall add rule name="websocketserver" dir=in action=allow protocol=tcp localport=12348
.
Also confirm the server is actually listening by running netstat -an | find "12348"
(or grep "12348"
on Linux). If it shows something with "listening" then it is working. Test first with a simple text message instead of an image to confirm the connection. Then move to sending binary data.
6 Comments
`
to format inline code and other elements - to make then more readable. You could also use ```
to format block of code/output/error (i.e. shell command)