イントロダクション(Introduction)
今まで悪戦苦闘してきましたが、ついに糸口を見つけました。(i was struggling to websocket)
人に聞いたりしてわかったこと(i found out by ask to my friends)
- Python2.Xは終わるらしいのでPython3.X以上を使う方が良い
- レンタルサーバーでやるならJS + PHPの方が早いかも?
- 人間諦めも必要だ
というわけで、サーバー、表示するクライアント画面はPHPで実装(i decided to use PHP)
Microbitでのシリアルデータの受信〜Webサーバーへの送信はPython3でやることにしました。
Python3.XならWebSocketクライアントを作れるので以下を参考に作成
https://websockets.readthedocs.io/en/stable/
Python WebSocket!
自分の環境では以下のモジュールが必要でした。ので下のコマンドでインストールします。(i had to install follow ing modules)
- asyncio
- websockets
ただ、上記のサイトには
pip install websockets
の様にコマンドを実行する様に記載してあったけど(i had used following command)
pip3 install websockets
の様にPython3を指定してやる必要がありました。
いざ!実装(Implementation)
<websocketSender.py>
import asyncio import websockets import json async def hello(): async with websockets.connect("ws://zenryokuservice.com:9000/demo/server.php") as websocket: mes = { 'message': 'MicrobitData', 'name': 'WebSocket.py', 'color': '#0B4C5F'} await websocket.send(mes) print(mes) asyncio.get_event_loop().run_until_complete(hello())
実行結果(Results)
アクセスするURLは
http://zenryokuservice.com/project/index.php
データやキャッシュを保存していないので一度画面を閉じると何も残りません。
そして、現状ではメッセージが全部「null」になっています。
修正しなくては。。。原因は送信するJSONデータがちゃんとJSONしていない様に睨んでいます。