PythonでWebSocketを使用するとき、クライアントがメッセージを送信した後、サーバーからのレスポンスを待つ必要があります。これにより、クライアントが前のレスポンスなしに2つのメッセージを連続して送信することはありません。
以下に、PythonでWebSocketを使用してレスポンスを待つ方法の一例を示します。
# server.py
import asyncio
import websockets
async def runServer():
server = await websockets.serve(onConnect, "localhost", port=8765)
print("Server started listening to new connections...")
await server.wait_closed()
async def onConnect(ws):
try:
while True:
message = await ws.recv()
if message == "msg1":
await ws.send("response from server 1")
elif message == "msg2":
await ws.send("response from server 2")
except websockets.exceptions.ConnectionClosedOK:
print("Client closed...")
if __name__ == "__main__":
asyncio.run(runServer())
# client.py
import asyncio
import websockets
async def connect():
async with websockets.connect("ws://localhost:8765") as ws:
print("Connected to the switch.")
await ws.send("msg1")
response = await ws.recv()
print("Response from the server:", response)
await ws.send("msg2")
response = await ws.recv()
print("Response from the server:", response)
if __name__ == "__main__":
asyncio.run(connect())
このコードでは、クライアントは最初に”msg1″を送信し、サーバーからのレスポンスを待ちます。レスポンスを受け取った後、”msg2″を送信し、再度レスポンスを待ちます。
このように、PythonとWebSocketを使用して非同期通信を行うことができます。ただし、このコードは基本的な例であり、実際のアプリケーションではエラーハンドリングや再接続のロジックなど、さらに考慮すべき事項があります。