前回はRaspberryPiとMacをLANケーブルで繋ぎSocket通信を行う方法を紹介しました。
RaspberryPiとMacでSocket通信(Python3)
今回はここ数年流行りのWebSocketを行う方法を紹介します。
RaspberryPiとMacをLANケーブルで繋ぐか、Wi-Fiで同じルーターに接続しておいてください。
RaspberryPiでサーバー側の実装
まずWebSocketを扱うライブラリをインストールします。
検索すると色々出てくるのですが、今回はWebsocketServerを使用します。
次のコマンドで最新のライブラリがインストールできます。
python3 -m pip install git+https://github.com/Pithikos/python-websocket-server
RaspberryPiの適当なディレクトに下記ファイルを作成します。
MyWebSocketServer.py
- #!/usr/bin/env python3
- from websocket_server import WebsocketServer
- import time
- def start():
- # クライアントが接続してきた時のイベント
- def new_client(client, server):
- print('New client {}:{} has joined.'.format(client['address'][0], client['address'][1]))
- time.sleep(2)
- # クライアントへメッセージ送信
- server.send_message(client, 'from server 1st message in new_client')
- time.sleep(2)
- # クライアントへメッセージ送信
- server.send_message(client, 'from server 2st message in new_client')
- # クライアントが切断した時のイベント
- def client_left(client, server):
- print('Client {}:{} has left.'.format(client['address'][0], client['address'][1]))
- # クライアントからのメッセージを受信した時のイベント
- def message_received(client, server, message):
- print(message)
- time.sleep(2)
- # クライアントへメッセージ送信
- server.send_message(client, 'from server 1st message in message_received')
- time.sleep(2)
- # クライアントへメッセージ送信
- server.send_message(client, 'from server 2st message in message_received')
- # 10005番ポートでサーバーを立ち上げる
- server = WebsocketServer(port=10005, host='0.0.0.0')
- # イベントで使うメソッドの設定
- server.set_fn_new_client(new_client)
- server.set_fn_client_left(client_left)
- server.set_fn_message_received(message_received)
- # 実行
- server.run_forever()
- if __name__ == "__main__":
- start()
Macでクライアント側の実装
Macの適当なディレクトに下記ファイルを作成します。
MyWebSocketClient.html
- <!DOCTYPE html>
- <html>
- <head>
- <script src="http://code.jquery.com/jquery-latest.min.js"></script>
- <script>
- $(function(){
- // RaspberryPiへ10005番ポートで接続
- var ws = new WebSocket("ws://raspberrypi.local:10005/");
- // サーバーからのメッセージ受信時のイベント
- ws.onmessage = function(message){
- $('textarea').val($('textarea').val() + message.data + '\n')
- }
- setTimeout(function(){
- // サーバーへメッセージ送信
- ws.send('from html');
- }, 6000)
- })
- </script>
- </head>
- <body>
- <textarea style="width:400px;height:100px"></textarea>
- </body>
- </html>
サーバー側の実行
RaspberryPiでサーバー側を実行します。
sudo を付けないとMac側から接続できないので注意が必要です。
sudo python3 MyWebSocketServer.py
クライアント側の実行
Macでクライアント側を実行します。
といってもHTMLファイルをブラウザで開くだけです。
実際の動き
- HTMLをリロードした途端、RaspberryPi(サーバー)へ接続
- RaspberryPi(サーバー)からMac(クライアント)へメッセージを2回送信
- Mac(クライアント)からRaspberryPi(サーバー)へメッセージを送信
- RaspberryPi(サーバー)からMac(クライアント)へメッセージを2回送信
という流れが確認できます。