1

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?

asked Oct 6 at 10:52

1 Answer 1

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.

charlotte
4606 silver badges18 bronze badges
answered Oct 6 at 11:54
Sign up to request clarification or add additional context in comments.

6 Comments

What if the two machines are not on the same wifi? How to proceed with that?
if the machines are not on the same wifi then the local ip will not work. you can set up port forwarding on the server’s router so your public ip points to port 12348 and connect the client using ws://your-public-ip:12348. make sure the port is open in the firewall. another option is to use a vpn or a cloud server so both machines can reach each other over the internet.
More specifically, if the two machines are not on the same network, you will have to configure your network to do "port forwarding" to the ports you are listening on. Generally, this is an option with your router (locally) or hosting provider (with a hosted server)
I'm saying "port forwarding" in quotes because that is the search terms you want to use to find more info about this, not because it's not actually called that
Should my code work for two machines on the same wifi? I am receiving a timeout in this case as well!
use ` 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)

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.