主函数
import tornado
import tornado.web
import tornado.ioloop
import tornado.websocket
import asyncio
import nest_asyncio
import json
nest_asyncio.apply()
#登录
class Login(tornado.web.RequestHandler):
def get(self):
self.render('login.html')
def post(self):
uname = self.get_argument('username')
password = self.get_argument('password')
if uname in ["zhangsan","lisi","wangwu"] and password=='123456':
self.set_cookie('uname',uname,expires_days=14)
self.redirect('/chat/')
else:
self.write('登录失败')
def set_default_header(self):
print("setting headers!!!")
self.set_header('Access-Control-Allow-Origin', '*')
# self.set_header('Access-Control-Allow-Origin', 'http://localhost:8080')
# self.set_header('Access-Control-Allow-Headers', 'X-Requested-With')
self.set_header('Access-Control-Allow-Headers', '*')
self.set_header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS')
self.set_header('Content-Type', 'application/json; charset=UTF-8')
self.set_header('Access-Control-Allow-Headers', 'Content-Type')
def options(self):
pass
#聊天室
class Chat(tornado.web.RequestHandler):
def get(self):
uname=self.get_cookie('uname')
self.render('chatroom.html',uname=uname)
#中转站weksocket
class Chatroom(tornado.websocket.WebSocketHandler):
online_users=[]
def open(self,*args,**kwargs):
print('有新用户链接我')
self.online_users.append(self)
def on_message(self,message):
print('接收到前端发送的消息',message)
uname = self.get_cookie('uname')
for user in self.online_users:
user.write_message(f'[{uname}]: {message}')
def on_close(self):
print('有用户以退出聊天室')
self.online_users.remove(self)
application = tornado.web.Application(
handlers=[
(r'/login/', Login),
(r'/chat/', Chat),
(r'/chatroom/', Chatroom),
]
)
if __name__ == '__main__':
application.listen(64826)
tornado.ioloop.IOLoop.current().start()
#登录网址:127.0.0.1:64826/login/
#账户号:["zhangsan","lisi","wangwu"]
#密码:123456
登录界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>登录</h2>
<hr>
<form action="" method="post">
<p>用户名:<input type="text" name="username"></p>
<p>密码:<input type="password" name="password"></p>
<p><input type="submit" value="登录"></p>
</form>
</body>
</html>
聊天界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>聊天室</h2>
<hr>
<p>
当前用户:{{ uname }}
</p>
<div style="width:400px; height:300px; border:1px solid gray; padding:10px;">
<div id="chatmsg">
</div>
</div>
<div>
<input type="text" id="msg">
<button id="send">发送</button>
</div>
<script>
ws = new WebSocket('ws://127.0.0.1:64826/chatroom/');
send.onclick = function(){
ws.send(msg.value);
msg.value=""
};
ws.onmessage = function (e){
p = document.createElement('p');
p.innerHTML = e.data;
chatmsg.appendChild(p);
}
</script>
</body>
</html>