一、案例实战主要代码
1、cha.py中的代码,处理聊天室的前端页面 RoomHandler类和处理相应发出的websocket通信的RoomWebSocket类
import tornado.websocket
import tornado.web
import datetime,time
import uuid
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient
from tornado import httputil
import tornado.escape #对json数据进行解码操作
from models.auth import User, Post, LikePost
from Handlers.main import BaseHandler
class RoomWebSocket(tornado.websocket.WebSocketHandler, BaseHandler):
waiters = set()
def open(self):
print("{}对象打开了WebSocket通信".format(self))
RoomWebSocket.waiters.add(self) #添加相应的连接对象
def on_close(self):
print("{}对象关闭了了WebSocket通信".format(self))
RoomWebSocket.waiters.remove(self)
def on_message(self, message):
# print("{}:{}".format(self, message))
parsed = tornado.escape.json_decode(message)
# if parsed['body'].startswith('http://'):
# client = AsyncHTTPClient()
# client.fetch(parsed['body'])
# api_url = 'http://127.0.0.1:8080/save?save_url={}'.format(parsed['body'])
# IOLoop.current().spawn_callback(client.fetch, api_url)
# msg = parsed['body']
# else:
# msg = parsed['body']
chat = {
'id': uuid.uuid4().hex,
'username': self.current_user,
'created': time.strftime("%y年%m月%d日 %H时%M分"),
'body': parsed['body']
}
chat['html'] = tornado.escape.to_basestring(self.render_string('chat/message.html', chat=chat))
for w in RoomWebSocket.waiters:
w.write_message(chat)
class RoomHandler(BaseHandler):
def get(self):
username = self.current_user
user = self.db_session.query(User).filter_by(username=username).first()
power_id = user.power
self.render('chat/room.html', username=username, power_id=power_id)
2、注册相应的路由
handlers=[ (r'/ws', chat.RoomWebSocket),(r'/room', chat.RoomHandler),]
3、room.html呈现聊天室的界面
{% extends ../base.html %}
{% block title %}
聊天室
{% end %}
{% block body %}
<div class="row" >
<div class="col-sm-3" style="color: #bee5eb"></div>
<div class="col-sm-6" style="border:3px solid orchid;background-color: #062c33">
<div id="inbox" style="color: #bee5eb;height:400px;overflow-y:auto"></div>
<div style="margin-top: 30px;border:3px solid blue;width:543px">
<form action="/ws" method="post" id="messageform">
<table >
<tr>
<td>
<input type="text" name="body" id="message" style="width: 470px">
</td>
<td style="padding-left: 5px">
<input class="btn btn-primary" type="submit" value="提交" style="font-size: 20px">
</td>
</tr>
</table>
</form>
</div></div>
<div class="col-sm-3" >col-sm-4</div>
</div>
{% end %}
{% block user %}
<li style="margin-left: 230px">
<a class="nav-link disabled" href="#">当前用户<i class="fa fa-user" aria-hidden="true" style="font-size: 25px;color: #ff6600"></i>:<font style="color: yellow">{{ username }}</font></a>
</li>
{% end %}
{% block script %}
<script src="../../static/js/chat.js"></script>
{% end %}
{% block upload_image_person %}
<a class="dropdown-item" href="/profile?username={{ username }}">查看上传和收藏的图片</a>
{% end %}