1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

python websocketのパッケージ整理

Last updated at Posted at 2022-02-18

目的

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

Pypi : Python Package Index

windows10 ファイアウォール

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

ファイアウォールを有効にするならば、ポートを開ける
image.png

ラズパイのファイアウォール

パッケージ確認

異なるパッケージなのにimport websocketが衝突している問題

pip install websocket
pip install websocket-client

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

websocket

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

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()
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?