python websocket client

from tornado.websocket import websocket_connect
from tornado.gen import coroutine, sleep


import logging
import logging.handlers
import json
from tornado.ioloop import IOLoop


__author__ = "Ennis"
SERVER_URL = "ws://192.168.1.208:7600/box/reader-"


def init_logging():
    """
    日志文件设置,每天切换一个日志文件
    :return:
    """
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)


    sh = logging.StreamHandler()
    file_log = logging.handlers.TimedRotatingFileHandler('scooter_notify.log', 'MIDNIGHT', 1, 0)
    formatter = logging.Formatter(
        '[%(asctime)s] [%(levelname)-7s] [%(module)s:%(filename)s-%(funcName)s-%(lineno)d] %(message)s')
    sh.setFormatter(formatter)
    file_log.setFormatter(formatter)


    logger.addHandler(sh)
    logger.addHandler(file_log)


    logging.info("Current log level is : %s", logging.getLevelName(logger.getEffectiveLevel()))


class Communicator:
    """
    负责与服务端交互,维持链路连接


    """
    close_door_timer = None


    def __init__(self):
        self._websocket_client = None


    @coroutine
    def on_recv_msg(self, message):
        try:
            if message is None:
                logging.info("web socket connection have disconnect, reconnect")
                yield self.on_websocket_close()
                return


            logging.info("receive message = %s", message)


        except Exception as err_info:
            logging.error("handle websocket message failed:%s", err_info)


    @coroutine
    def on_websocket_close(self):
        while True:
            try:
                self._websocket_client = None
                yield sleep(1)
                self._websocket_client = yield websocket_connect(SERVER_URL, on_message_callback=self.on_recv_msg)
                break


            except Exception as err_info:
                print(err_info)
                continue
        logging.info("connect server success:%s", SERVER_URL)


    @coroutine
    def start(self):
        """


        :return:
        """
        try:
            websocket_connect(SERVER_URL, on_message_callback=self.on_recv_msg)
            self._websocket_client = yield websocket_connect(SERVER_URL, on_message_callback=self.on_recv_msg)
            logging.info("connect server success:%s", SERVER_URL)


        except Exception as err_info:
            logging.error("start device controller failed: %s", err_info)
            yield self.on_recv_msg(None)


    @coroutine
    def send_data(self, data):
        try:
            logging.info("will post device central :%s", data)
            if self._websocket_client is None:
                return False


            self._websocket_client.write_message(data)
            return True


        except Exception as err_info:
            logging.error("send dat to service failed: %s", err_info)

            return False


websocket客户端,声明该类对象后,调用start函数,在调用 IOLoop.instance().start()之后生效

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值