为啥是Websocket
- 服务端可以主动推送消息到浏览器端。比如服务端实时在打印日志,这是一个标准输出,可以实时将日志推送到浏览器。
举例
import datetime,time
from sys import stdout
while True:
now = time.strftime("%Y-%m-%d %H:%M:%S")
print now
stdout.flush()
time.sleep(2)
root@ubuntu:~# python test.py
2018-12-17 09:57:37
2018-12-17 09:57:39
2018-12-17 09:57:41
2018-12-17 09:57:43
2018-12-17 09:57:45
2018-12-17 09:57:47
root@ubuntu:~# websocketd --port=9000 python test.py
<!DOCTYPE html>
<html>
<head>
<title>websocketd example</title>
<style>
#count {
font: bold 150px arial;
margin: auto;
padding: 10px;
text-align: center;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<table border="1px #ooo" id="logtable" cellpadding="0"
cellspacing="0" width="30%">
<tr align="center">
<td width="100%">log</td>
</tr>
</table>
<script>
function addTr(tab, row, trHtml){
var $tr=$("#"+tab+" tr").eq(row);
if($tr.size()==0){
alert("id not exit");
return;
}
$tr.after(trHtml);
};
//addTr('logtable', -1, 'xxxxxxxxxx');
var ws = new WebSocket('ws://' + (location.host ? location.host : "localhost:9000") + "/");
ws.onopen = function() {
document.body.style.backgroundColor = '#cfc';
};
ws.onclose = function() {
document.body.style.backgroundColor = null;
};
ws.onmessage = function(event) {
console.log(event.data);
//document.getElementById('count').textContent = event.data;
addTr('logtable', -1, '<tr><td>' + event.data + '</td></tr>')
};
</script>
</body>
</html>