WebSocket -Kommunikation zwischen Server und Client in PythonPython

Python-Programme
Anonymous
 WebSocket -Kommunikation zwischen Server und Client in Python

Post by Anonymous »

Ich möchte eine Websocket -Kommunikation zwischen meinem persönlichen Laptop und einem Server erstellen. Ich habe den Client.py und server.py erstellt und sie sehen wie folgt aus:
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())
Wenn ich sowohl Server als auch die Client ausführe, werden die Programme ausgeführt, aber ich erhalte keine Reaktion vom Server. Gibt es etwas, das ich anders machen muss? Stimmt etwas mit meinem Code nicht?

Code: Select all

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 Um mit dem IP des Servers eine Verbindung zu meinem Server herzustellen. Ist das das richtige zu tun?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post