-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 8ea01a0
Showing
4 changed files
with
322 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,146 @@ | ||
#-*-coding:utf-8-*- | ||
__author__ = '高志广' | ||
import json | ||
import tornado.web | ||
import tornado.websocket | ||
import tornado.httpserver | ||
import tornado.ioloop | ||
import tornado.options | ||
import datetime | ||
from uuid import uuid4 | ||
|
||
lit = ["聊天室一","聊天室二"] | ||
|
||
class ChatHome(object): | ||
''' | ||
处理websocket 服务器与客户端交互 | ||
''' | ||
chatRegister = {} | ||
def register(self, newer): | ||
''' | ||
保存新加入的客户端连接、监听实例,并向聊天室其他成员发送消息! | ||
''' | ||
home = str(newer.get_argument('n')) #获取所在聊天室 | ||
if home in self.chatRegister: | ||
self.chatRegister[home].append(newer) | ||
else: | ||
self.chatRegister[home] = [newer] | ||
|
||
message = { | ||
'from': 'sys', | ||
'message': '%s 加入聊天室(%s)' % (str(newer.get_argument('u')), home), | ||
'time': '当前时间:(%s)' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) | ||
} | ||
self.callbackTrigger(home, message) | ||
|
||
def unregister(self, lefter): | ||
''' | ||
客户端关闭连接,删除聊天室内对应的客户端连接实例 | ||
''' | ||
home = str(lefter.get_argument('n')) | ||
self.chatRegister[home].remove(lefter) | ||
if self.chatRegister[home]: | ||
message = { | ||
'from': 'sys', | ||
'message': '%s 离开聊天室(%s)' % (str(lefter.get_argument('u')), home), | ||
'time': '(%s)' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) | ||
} | ||
self.callbackTrigger(home, message) | ||
|
||
def callbackNews(self, sender, message): | ||
''' | ||
处理客户端提交的消息,发送给对应聊天室内所有的客户端 | ||
''' | ||
home = str(sender.get_argument('n')) | ||
user = str(sender.get_argument('u')) | ||
message = { | ||
'from': user, | ||
'message': message, | ||
'time': '(%s)' % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) | ||
} | ||
self.callbackTrigger(home, message) | ||
|
||
def callbackTrigger(self, home, message): | ||
''' | ||
消息触发器,将最新消息返回给对应聊天室的所有成员 | ||
''' | ||
for callbacker in self.chatRegister[home]: | ||
callbacker.write_message(json.dumps(message)) | ||
|
||
|
||
|
||
class homeHandler(tornado.web.RequestHandler): | ||
''' | ||
聊天室, 获取主页选择聊天室跳转的get信息渲染页面 | ||
''' | ||
def get(self, *args, **kwargs): | ||
n = self.get_argument('n') #聊天室 | ||
u = self.get_argument('u') #用户 | ||
self.render('chat/home.html', n=n, u=u) | ||
|
||
|
||
|
||
class newChatStatus(tornado.websocket.WebSocketHandler): | ||
''' | ||
websocket, 记录客户端连接,删除客户端连接,接收最新消息 | ||
''' | ||
def open(self): | ||
n = str(self.get_argument('n')) | ||
self.write_message(json.dumps({'from':'sys', 'message':'欢迎来到 聊天室(%s)' % n,'time':'(%s)' %(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))})) #向新加入用户发送首次消息 | ||
self.application.chathome.register(self) #记录客户端连接 | ||
|
||
def on_close(self): | ||
self.application.chathome.unregister(self) #删除客户端连接 | ||
|
||
def on_message(self, message): | ||
self.application.chathome.callbackNews(self, message) #处理客户端提交的最新消息 | ||
|
||
|
||
class mainHandler(tornado.web.RequestHandler): | ||
# 主页, 用户登录界面 | ||
def get(self): | ||
self.render('chat/login.html') | ||
|
||
class loginHandler(tornado.web.RequestHandler): | ||
#进入聊天室选择界面 | ||
def post(self): | ||
persion = self.get_argument("username") | ||
print(persion) | ||
self.render('chat/basic.html', session = persion, set1=lit) | ||
|
||
class tuichuHandler(tornado.web.RequestHandler): | ||
def post(self): | ||
persion = self.get_argument("u") | ||
print(persion) | ||
self.render('chat/basic.html', session = persion, set1=lit) | ||
|
||
class CreateHandler(tornado.web.RequestHandler): | ||
def post(self): | ||
a = self.get_argument("roomname") | ||
persion = self.get_argument("session") | ||
print(a) | ||
lit.append(a) | ||
print(lit) | ||
self.render("chat/basic.html", session=persion, set1=lit) | ||
class Application(tornado.web.Application): | ||
def __init__(self): | ||
self.chathome = ChatHome() | ||
handlers = [ | ||
(r'/home/', homeHandler), | ||
(r'/newChatStatus/', newChatStatus), | ||
(r'/', mainHandler), | ||
(r'/login', loginHandler), | ||
(r'/tuichu',tuichuHandler), | ||
(r'/create',CreateHandler), | ||
] | ||
settings = { | ||
'template_path': 'html', | ||
'static_path': 'static' | ||
} | ||
tornado.web.Application.__init__(self, handlers, **settings) | ||
|
||
if __name__ == '__main__': | ||
tornado.options.parse_command_line() | ||
server = tornado.httpserver.HTTPServer(Application()) | ||
server.listen(8000) | ||
tornado.ioloop.IOLoop.instance().start() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="UTF-8"> | ||
<title>房间选择页面</title> | ||
</head> | ||
<body style="background: antiquewhite;"> | ||
<form> | ||
<h1>你好 !{{ session }} <br> 欢迎来到聊天室!</h1> | ||
<input type="hidden" value="{{ set1 }}" id="set1" name="set1"> | ||
<h1>现在存在{{ set1 }}聊天室</h1> | ||
<h1>and you can create a chat room</h1> | ||
</form> | ||
|
||
<form method="post" action="/create"> | ||
<div class="main" id="main"> | ||
<h1>please input the name of the chatroom</h1> | ||
<input type="text" name="roomname" id="roomname"> | ||
<input type="hidden" value="{{ session }}" id="session" name="session"> | ||
<!--input type="button" onclick="inputname()" value="create"--> | ||
<br> | ||
<input type="submit" value="yes"> | ||
<br> | ||
</div> | ||
</form> | ||
|
||
|
||
|
||
<script> | ||
var number=2; | ||
function inputname() { | ||
//var x; | ||
//var chat_name = prompt("请输入聊天室名称","聊天室三"); | ||
var chat_name = document.getElementById("roomname").value; | ||
if (chat_name!=null && chat_name!=""){ | ||
//x="你好 ,已创建聊天室" + chat_name ; | ||
//document.getElementById("demo").innerHTML=x; | ||
var a=document.createElement("a"); | ||
var b=document.createElement("br"); | ||
number=number+1; | ||
a.href= "/home/?n=" + number + "&u={{ session }}"; | ||
a.innerText = chat_name; | ||
//$('#increase').appendChild(a); | ||
//$('#increase').appendChild(b); | ||
document.body.appendChild(a); | ||
document.body.appendChild(b); | ||
} | ||
} | ||
window.onload=function() { | ||
var set1= document.getElementById("set1").value; | ||
//alert(set1); | ||
//var myset = new Array(); | ||
var myset = set1.split(","); | ||
alert(myset) | ||
for (var i = 2; i < myset.length; i++) { | ||
var a = document.createElement("a"); | ||
var b = document.createElement("br"); | ||
a.href = "/home/?n=" + (i+1) + "&u={{ session }}"; | ||
a.innerText = myset[i].slice(1,-1); | ||
document.body.appendChild(a); | ||
document.body.appendChild(b); | ||
} | ||
} | ||
|
||
</script> | ||
|
||
<a href="/home/?n=1&u={{ session }}"> 聊天室一 </a> <br> | ||
<a href="/home/?n=2&u={{ session }}"> 聊天室二 </a> <br> | ||
</body> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,88 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="UTF-8"> | ||
<title>聊天页面</title> | ||
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js"></script> | ||
<script> | ||
$(function(){ | ||
n = $("#n").val() | ||
u = $("#u").val() | ||
historyname = n+u | ||
$("#btn").click(function(){ | ||
sendText() | ||
localStorage.setItem(historyname,document.getElementById("chatinfo").innerHTML)//保存历史记录 | ||
}) | ||
function requestText(){ | ||
host = "ws://localhost:8000/newChatStatus/?n=" + n + "&u=" +u | ||
websocket = new WebSocket(host) | ||
|
||
websocket.onopen = function(evt){ | ||
$('#chathistory').append(localStorage.getItem(historyname)) | ||
} // 建立连接 | ||
websocket.onmessage = function(evt){ // 获取服务器返回的信息 | ||
data = $.parseJSON(evt.data) | ||
if(data['from']=='sys'){ // 如果是系统信息,则显示在中间 | ||
$('#chatinfo').append("<p style='width: 100%; text-align:center; " + | ||
"font-size: 16px; color: green'>" + data['message'] +data['time']+ "</p>"); | ||
}else if(data['from']==u){ //如果是本人发送的信息,则显示在右边 | ||
$('#chatinfo').append("<p style='width: 100%; text-align:right; " + | ||
"font-size:15px'>" + u + ": <br>" +"<span style='color: blue'>" + data['message'] + "</span>" + "</p>"); | ||
}else{ //如果是聊天对象的信息,显示在左边 | ||
$('#chatinfo').append("<p style='width: 100%; text-align:left; font-size:15px'>"+ data['time'] + data['from'] + ": <br>" +"<span style='color: red'>" + data['message'] + "</span>" + "</p>"); | ||
} | ||
localStorage.setItem(historyname,document.getElementById("chatinfo").innerHTML)//保存历史记录 | ||
} | ||
websocket.onerror = function(evt){} | ||
} | ||
|
||
requestText() // 开始 websocket连接,并开始接收信息 | ||
|
||
function sendText(){ // 向服务器发送信息 | ||
websocket.send($("#chat_text").val()) | ||
} | ||
$("#clean").click(function(){ | ||
$('#chathistory').empty();//清空文本 | ||
localStorage.setItem(historyname,"")//清空历史记录 | ||
}) | ||
} | ||
) | ||
//可使用<meta http-equiv="refresh" content="3">刷新网页解决无法自动显示聊天记录的为问题。。但是这个东西把历史记录也刷新掉了 | ||
</script> | ||
</head> | ||
<body> | ||
<div align="center"> | ||
<form method="post" action="/tuichu"> | ||
<div style="width: 70% ;background: aquamarine"> | ||
<h1>聊天室({{ n }})!</h1> | ||
<input type="hidden" value="{{ n }}" id="n" name="n"> | ||
<input type="hidden" value="{{ u }}" id="u" name="u"> | ||
<input type="submit" value="退出此聊天室"> | ||
</div> | ||
</form> | ||
<div style="width: 70% ;background: aquamarine"> | ||
<div id="chatinfo" style="padding:10px;border: 1px solid #888"> | ||
<!-- 聊天内容,将聊天内容显示在此,通过append方法 --> | ||
</div> | ||
|
||
<div style="clear: both; text-align:right; margin-top: 20px"> | ||
<input type="text" name="chat_text" id="chat_text"> | ||
<button id="btn" style="width: border-box;border: #00FF00;background: brown">发送</button> | ||
</div> | ||
</div> | ||
</div> | ||
<div align="center"> | ||
<div style="width: 40%"> | ||
<h1>聊天室({{ n }})</h1> | ||
<input type="hidden" value="{{ n }}" id="n"> | ||
<input type="hidden" value="{{ u }}" id="u"> | ||
|
||
<div id="chathistory" style="padding:20px;border: 1px solid #888"> | ||
<button id="clean">清空聊天记录</button> | ||
<!-- 历史聊天内容 --> | ||
<p>聊天记录</p> | ||
</div> | ||
</div> | ||
</div> | ||
</body> | ||
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="UTF-8"> | ||
<title>login</title> | ||
</head> | ||
<body style="background: aquamarine;align-items: center"> | ||
<div align="center" style="font-size:14px; color:#00FF00;background:#000;" > | ||
<form method="post" action="/login"> | ||
<h1>please input your username that you want to use at chatting rooms</h1> | ||
<input type="text" name="username"> | ||
<br> | ||
<input type="submit" value="yes"> | ||
</form> | ||
</div> | ||
|
||
</body> | ||
</html> |