python3知识点
web服务器代码:
#coding=utf-8
importtornado.websocket
importtornado.web
importtornado.ioloop
importdatetime
classIndexHandler(tornado.web.RequestHandler):
defget(self, *args, **kwargs):
self.render('templates/index.html')
classWebHandler(tornado.websocket.WebSocketHandler):
users =set()#存放在线用户
defopen(self, *args, **kwargs):
self.users.add(self)#把建立连接后的用户添加到用户容器中
foruserinself.users:#向在线的用户发送进入消息
user.write_message("[%s]-[%s]-进入聊天室"% (self.request.remote_ip,
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
defon_close(self):
self.users.remove(self)# 用户关闭连接后从容器中移除用户
foruserinself.users:
user.write_message("[%s]-[%s]-离开聊天室"% (self.request.remote_ip,
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
defon_message(self, message):
foruserinself.users:#向在线用户发送聊天消息
user.write_message("[%s]-[%s]-说:%s"% (self.request.remote_ip,
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), message))
defcheck_origin(self, origin):
return True# 允许WebSocket的跨域请求
importos
BASE_DIR = os.path.dirname(__file__)
settings = {
'static_path':os.path.join(BASE_DIR,'static'),
"websocket_ping_interval":1,
"websocket_ping_timeout":10
}
app = tornado.web.Application([(r'/',IndexHandler),
(r'/chat',WebHandler)],
**settings)
app.listen(8009)
tornado.ioloop.IOLoop.instance().start()
HTML代码:python3知识点
微信QQ
#chatcontent{
/*显示内容使用的*/
width:500px;
height:200px;
background-color:pink;
overflow-y:scroll;
overflow-x:scroll;
}
发送
ws=newWebSocket('ws://192.168.1.27:8009/chat')
//服务器给浏览器推送消息的时候回调
ws.onmessage=function(p1) {
$('#chatcontent').append('
'+p1.data+'
')
}
functionsend() {
varcontent=$('#msg_container').val()
ws.send(content)
$('#msg_container').val('')
}
网友评论