Erstens den Server:
Code: Select all
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())
< /code>
Und dann der Client: < /p>
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())
Code: Select all
raise TimeoutError("timed out during opening handshake") from exc TimeoutError: timed out during opening handshake
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 Um mit dem IP des Servers eine Verbindung zu meinem Server herzustellen. Ist das das richtige zu tun?