|
import asyncio
|
|
import websockets
|
|
import json
|
|
import time
|
|
|
|
|
|
shared_data = {
|
|
"latest_sensor_data": None,
|
|
"last_message_time": None
|
|
}
|
|
|
|
|
|
async def handle_client(websocket, path):
|
|
global shared_data
|
|
while True:
|
|
try:
|
|
|
|
message = await websocket.recv()
|
|
print(f"受信したメッセージ: {message}")
|
|
|
|
|
|
if message == "ping":
|
|
await websocket.send("pong")
|
|
continue
|
|
|
|
|
|
sensor_data = json.loads(message)
|
|
shared_data["latest_sensor_data"] = sensor_data
|
|
shared_data["last_message_time"] = time.time()
|
|
|
|
|
|
print(f"最新センサーデータ: {shared_data['latest_sensor_data']}")
|
|
except websockets.ConnectionClosed:
|
|
print("クライアントとの接続が切断されました")
|
|
break
|
|
|
|
|
|
async def main():
|
|
async with websockets.serve(handle_client, "localhost", 8765):
|
|
print("WebSocketサーバーが起動しました。")
|
|
await asyncio.Future()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main()) |