服务端代码
importdatetimefromabcimportABCimporttornado.httpserverimporttornado.ioloopimporttornado.webfromtornado.optionsimportdefine, optionsfromtornado.websocketimportWebSocketHandlerdefine("host", default="127.0.0.1", type=str) define("port", default=8000, type=int) classChatHandler(WebSocketHandler, ABC): users=set() # 用来存放在线用户的容器defopen(self): self.users.add(self) # 建立连接后添加用户到容器中foruinself.users: # 向已在线用户发送消息u.write_message( f"[{self.request.remote_ip}]-[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]-进入聊天室") defon_message(self, message): foruinself.users: # 向在线用户广播消息u.write_message(u"[%s]-[%s]-说:%s"% ( self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), message)) defon_close(self): self.users.remove(self) # 用户关闭连接后从容器中移除用户foruinself.users: u.write_message( f"[{self.request.remote_ip}]-[{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}]-离开聊天室") defcheck_origin(self, origin): returnTrue# 允许WebSocket的跨域请求if__name__=='__main__': app=tornado.web.Application([ (r"/", ChatHandler), ]) http_server=tornado.httpserver.HTTPServer(app) http_server.listen(options.port) print(f"http://{options.host}:{options.port}") tornado.ioloop.IOLoop.current().start()
客户端代码:
#!/usr/bin/env python3# -*- coding: utf-8 -*-importtimeimportwebsocketimport_thread# 在接收到服务器发送消息时调用defon_message(ws, message): print('Received: '+message) # 在和服务器建立完成连接时调用defon_open(ws): # 线程运行函数defprocess(): whileTrue: s=input("要发送的内容(quit表示退出):") ifs=="quit": breakws.send(s) # 休息 0.2 秒先接收服务器回复的消息time.sleep(0.2) # 关闭 Websocket 的连接ws.close() print("Websocket closed") # 在另一个线程运行 gao() 函数_thread.start_new_thread(process, ()) if__name__=="__main__": ws=websocket.WebSocketApp("ws://127.0.0.1:8000/", on_message=on_message, on_open=on_open) ws.run_forever()
实例: