websocket本身是一种持久化协议,与普通http协议不同,他是一种可以主动从服务器向浏览器发送的消息的协议,不过开始还是需要http协议建立连接.
优点:
1:持久化连接,只要不主动断开连接,就可以一直发送消息
2:减少资源浪费
示例代码:实时显示日志信息到前端页面
服务端代码
import subprocess
import asyncio
import websockets
log_path = '/Users/logs/messages.log'
async def _connect(websocket):
cmd = "/usr/bin/tail -f {log_path}".format(log_path=log_path)
popen=subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
while True:
line=popen.stdout.readline().strip()
if line:
await websocket.send(line)
else:
return
async def user_connect(websocket,path):
await _connect(websocket)
start_server = websockets.serve(user_connect,'127.0.0.1', 5678)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
前端代码:
<!DOCTYPE html>
<html>
<head>
</head>
<style>
#msg{
width:400px; height:400px; overflow:auto; border:2px solid #000000;background-color:#000000;color:#ffffff;
}
</style>
</head>
<body>
<p>实时日志</p>
<div id="msg"></div>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
/* !window.WebSocket、window.MozWebSocket检测浏览器对websocket的支持*/
if (!window.WebSocket) {
if (window.MozWebSocket) {
window.WebSocket = window.MozWebSocket;
} else {
$('#msg').prepend("<p>你的浏览器不支持websocket</p>");
}
}
/* ws = new WebSocket 创建WebSocket的实例 注意设置对以下的websocket的地址哦*/
ws = new WebSocket('ws://127.0.0.1:5678/websocket/');
/*
ws.onopen 握手完成并创建TCP/IP通道,当浏览器和WebSocketServer连接成功后,会触发onopen消息
ws.onmessage 接收到WebSocketServer发送过来的数据时,就会触发onmessage消息,参数evt中包含server传输过来的数据;
*/
ws.onopen = function(evt) {
$('#msg').append('<li>websocket连接成功</li>');
}
ws.onmessage = function(evt) {
$('#msg').prepend('<li>' + evt.data + '</li>');
}
});
</script>
</body>
</html>