python中websocket、socket、http的区别
1. 相同点
(1)都是基于TCP的,都是可靠的传输协议
(2)都是应用层协议
2. 不同点
(1)websocket是双向通信协议,模拟socket协议,可以双向发送或接收消息,http是单向的
3. 联系
websocket在建立握手时,数据是通过http传输的,当建立连接成功后,在数据传输时不是通过Http而是通过单独建立的tcp通道传输的。
websocket:它实现了浏览器与服务器全双工(full-duplex)通信。其本质是保持TCP连接,在浏览器和服务端通过Socket进行通信。
4. tornado实现websocket聊天室
app.py文件代码
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
import os
import datetime
from tornado.web import RequestHandler
from tornado.options import define, options
from tornado.websocket import WebSocketHandler
define("port", default=8000, type=int)
class IndexHandler(RequestHandler):
def get(self):
self.render("index.html")
class ChatHandler(WebSocketHandler):
cli = set() # 用来存放在线用户的容器
def open(self):
print(self.request)
self.cli.add(self) # 建立连接后添加用户到容器中
for c in self.cli: # 向已在线用户发送消息
c.write_message(
u"[%s]-[%s]-进入聊天室" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
def on_message(self, message):
for c in self.cli: # 向在线用户广播消息
c.write_message(u"[%s]-[%s]-说:%s" % (
self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), message))
def on_close(self):
self.cli.remove(self) # 用户关闭连接后从容器中移除用户
for c in self.cli:
c.write_message(
u"[%s]-[%s]-离开聊天室" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
def check_origin(self, origin):
return True # 允许WebSocket的跨域请求
if __name__ == '__main__':
tornado.options.parse_command_line()
app = tornado.web.Application([
(r"/", IndexHandler),
(r"/chat", ChatHandler),
],
static_path=os.path.join(os.path.dirname(__file__), "static"),
template_path=os.path.join(os.path.dirname(__file__), "template"),
debug=True
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
tornado.ioloop.IOLoop.current().start()
index.html文件?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>聊天室</title>
</head>
<style type="text/css">
#char{
margin: 0 auto;
height:500px;
width: 800px;
}
#contents{
height:500px;
width: 800px;
border:1px solid #cccccc;
border-radius:3px;
box-shadow: 2px 2px 5px #888888;
margin-bottom: 10px;
}
.input_send #msg{
height:20px;
width: 757px;
}
</style>
<body>
<div id="char" >
<div id="contents"></div>
<div class="input_send">
<textarea id="msg"></textarea>
<a href="javascript:;" id="send_mesage" onclick="sendMsg()">发送</a>
</div>
</div>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"></script>
<!--<script src="{{static_url('js/jquery.min.js')}}"></script>-->
<script type="text/javascript">
// var ws = new WebSocket("ws://127.0.0.1:8000/chat");
var ws = new WebSocket("ws://192.168.110.30:8000/chat");
ws.onmessage = function(e) {
$("#contents").append("<p>" + e.data + "</p>");
}
function sendMsg() {
var msg = $("#msg").val();
ws.send(msg);
$("#msg").val("");
}
</script>
</body>
</html>
|