websocket 服务端(tornado)

import tornado.ioloop
import tornado.web
import tornado.websocket
from tornado.options import define, options, parse_command_line
from tornado import gen

define("port", default=9993, help="run on the port", type=int)

clients = dict()

class IndexHandler(tornado.web.RequestHandler):  
    @tornado.gen.coroutine
    def get(self):
        self.write("<h1>IndexHandler calling</h1>")
        self.render("xxx.html")  #html可以包含websocket客户端实现链接

class MyWebsocketHandler(tornado.websocket.WebSocketHandler):
    @tornado.gen.coroutine
    def get(self):   #路由显示
        self.write("<h1>waiting for clients conenct!</h1>")
    def open(self, *args):  #新链接调用
        slef.id = self.get_argument("Id")
        self.stream.set_nodelay(True)
        clients[self.id] = {"id":self.id, "object":self}

    def on_message(self, message): #收到信息时调用
        print("client %s received a message:%s "%(self.id, message))

    def on_close(self):  #链接关闭时调用
        if self.id in clients:
            del clients[self.id]
            print("client %s is closed"%(self.id))

    def check_origin(self, origin):
        return True


app = tornado.web.Application([(r'/',IndexHandler),(r'/websocket', MyWebsocketHandler),])  #双路由

import threading
import time

def send_time():  #向所有的客户端发送当前时间
    import datetime
    while True:
        for key in clients.keys():
            msg = str(datetime.datetime.now())
            clients[key]["object"].write_message(msg)
            print("write to cleint %s : %s"%(key, msg))
        time.sleep(1)

if __name__ == "__main__":
    threading.Thread(target=send_time).start() #启动当前线程推送时间
    parse_command_line()
    app.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()#挂起运行

tornado自己提供的websocket库以外,也可以自己构建websocket服务器!博客中有!

猜你喜欢

转载自blog.csdn.net/weixin_42694291/article/details/84026215