基于reactjs+python tornado实现websocket

const { location, WebSocket } = global

connectWebsoket() {
    this.ws = new WebSocket(WEBSOCKET_URL)
	this.ws.onopen = () => {
		console.log(WEBSOCKET_URL,'websocket已连接')
		//可以处理一些身份验证
	}
	
	this.ws.onmessage = (e) => {
	     console.log('消息接收成功',e.data)
		let res = JSON.parse(e.data)
		
	
	}
	this.ws.onerror = () => {
      console.log('消息服务器未连接,请检查是否开启cookie支持,再重新登录!')
    }
	
	this.ws.onclose = (e) => {
      console.log('webSocket已断开, 3秒后开始重连')
      setTimeout(() => {
        this.connectWebsoket()
      }, 3000)
    }
	
}
try:
    import cPickle as pickle
except:
    import pickle
import tornado.gen
import tornado.tcpclient
import time

class Message(object):
    def __init__(self, address, port, timeout=120):
        self._client = tornado.tcpclient.TCPClient()
        self.watches = set()
        self.address = address
        self.port = port
        self.timeout = timeout



    def add_client(self, user_id, socket):
        self.watches.add((uid, socket))
    
	
    def close(self, socket):
        logging.info('watches remove: %s' % socket.pid)
        for i in filter(lambda x:x[2]==socket, self.watches):
            self.watches.remove(i)
			
	
    @tornado.gen.coroutine
    def listen(self):
		try:
			logging.info('notify server: connect...')
			self.stream = yield self._client.connect(self.address, self.port)
        except:
            logging.warning('notify server: connect failed')
            self.connected = False
            tornado.ioloop.IOLoop.instance().add_timeout(time.time()+self.timeout, self.listen)
		else:
			data = yield self.stream.read_until('\r\n')
			message, operator_ids = pickle.loads(data)
			//发送
			self.new_messages(message,operator_ids)


    def new_messages(self, message, operator_ids=None):
        # 发送到所有客户端
        logging.info("Sending new message to %r listeners", len(self.watches))
        for uid, socket in self.waiters:
            if  (operator_ids and uid in operator_ids):
                try:
                    socket.write_message(message)
                except:
                    logging.error("Error in watches callback", exc_info=True)
					
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值