python websocketのパッケージ整理

# 目的
似て非なるパッケージが複数あって混乱するので整理したい。
websocket系とthread

# Pypi : Python Package Index
https://pypi.org/

# windows10 ファイアウォール
外部への線を抜いてローカルでファイアウォールを切る。

https://pc-karuma.net/windows-10-firewall-enable-disable/#Windows_%E3%83%95%E3%82%A1%E3%82%A4%E3%82%A2%E3%82%A6%E3%82%A9%E3%83%BC%E3%83%AB%E3%82%92%E7%84%A1%E5%8A%B9%E3%81%AB%E3%81%99%E3%82%8B

ファイアウォールを有効にするならば、ポートを開ける
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/555658/68257047-39c0-a7fb-de9c-6bc71892435d.png)

# ラズパイのファイアウォール
https://qiita.com/leelan324/items/c44aeeb2bab4e4ee9c0a

# パッケージ確認
https://make-muda.net/2017/10/5645/

# 異なるパッケージなのにimport websocketが衝突している問題
https://qiita.com/ikentoh/items/34b980da07bfc8abfd81

pip install websocket
pip install websocket-client

どちらも import websocket になる。これが問題。

# websocket
pip install websocket
https://pypi.org/project/websocket/

# websocket-client
https://pypi.org/project/websocket-client/

import websocket

```
import websocket
print(websocket.__version__)
```

```
1.2.3
```
となるので、一致している（pip listの結果と一致）

# 参考：以前ためしたやつ
https://www.raspberrypirulo.net/entry/websocket-server
https://make-muda.net/2017/10/5645/

# thread から　import threading版
上記URLを引数でIP・PORT
PORTを指定して、threading利用に変更したコード


スレッド
https://docs.python.org/ja/3/library/threading.html


```

import websocket
import threading

import time
import logging
import sys

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(' %(module)s -  %(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
 
# Callback functions
 
def on_message(ws, message):
  logger.info('Received:{}'.format(message))
 
def on_error(ws, error):
  logger.info('Error:{}'.format(error))
 
def on_close(ws):
  logger.info('Close')

class MyThread(threading.Thread):
  def run(self):
    # some heavy processing
    logger.info('Open')
    for i in range(3):
      time.sleep(1)
      message = "Hello " + str(i)
      ws.send(message)
      logger.info('Sent:{}'.format(message))
    time.sleep(1)
    ws.close()
    logger.info('Thread terminating...')

def on_open(ws): 

  def run(*args):
    logger.info('Open')
    for i in range(3):
      time.sleep(1)
      message = "Hello " + str(i)
      ws.send(message)
      logger.info('Sent:{}'.format(message))
    time.sleep(1)
    ws.close()
    logger.info('Thread terminating...')

  #thread.start_new_thread(run, ())
  t = MyThread()
  t.start() 

# Main
 
if __name__ == "__main__":
  args = sys.argv
  if 3 > len(args):
    print("usage : python3 ***.py ip port")
    exit(1)

  ipaddr = args[1]
  port = args[2]
  print(ipaddr)
  print(port)

  #websocket.enableTrace(True)
  websocket.enableTrace(False)
  szurl = "ws://" + ipaddr + ":" + port
  print(szurl)
  ws = websocket.WebSocketApp(szurl, #"ws://127.0.0.1:9876",
                            on_message = on_message,
                            on_error = on_error,
                            on_close = on_close)
  ws.on_open = on_open
  ws.run_forever()


```

# server

```
import logging
from websocket_server import WebsocketServer
import sys

logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(' %(module)s -  %(asctime)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)
 
# Callback functions
 
def new_client(client, server):
  logger.info('New client {}:{} has joined.'.format(client['address'][0], client['address'][1]))
 
def client_left(client, server):
  logger.info('Client {}:{} has left.'.format(client['address'][0], client['address'][1]))
 
def message_received(client, server, message):
  logger.info('Message "{}" has been received from {}:{}'.format(message, client['address'][0], client['address'][1]))
  reply_message = 'Hi! ' + message
  server.send_message(client, reply_message)
  logger.info('Message "{}" has been sent to {}:{}'.format(reply_message, client['address'][0], client['address'][1]))
 
# Main
if __name__ == "__main__":
  args = sys.argv
  if 3 > len(args):
    print("usage : python3 ***.py ip port")
    exit(1)

  ipaddr = args[1]
  port = int(args[2])
  print(ipaddr)
  print(port)
  print("--------------------")
  server = WebsocketServer(port=port, host=ipaddr, loglevel=logging.INFO)
  server.set_fn_new_client(new_client)
  server.set_fn_client_left(client_left)
  server.set_fn_message_received(message_received)
  server.run_forever()
```