爲什麼要用webSocket?

最近在接觸goaccess 可視化Nginx的log,遇到一個問題: 如何在瀏覽器中實時展示Nginx的請求?

將access log實時輸出到指定位置,其中

goaccess /usr/local/nginx/logs/access.log -o /opt/goaccess/html/out.html --real-time-html --time-format='%H:%M:%S'  --date-format='%d/%b/%Y' --log-format=COMBINED --port=7000 --daemonize

實時數據更新是 瀏覽器和goaccess的WebSocket連接獲取。

WebSocket  使得實時監控服務器,簡直是輕而易舉

WebSocket 是一種網絡通信協議,很多高級功能都需要它。

初次接觸 WebSocket 的人,都會問同樣的問題:我們已經有了 HTTP 協議,爲什麼還需要另一個協議?它能帶來什麼好處?

答案很簡單,因爲 HTTP 協議有一個缺陷:通信只能由客戶端發起。

舉例來說,我們想了解今天的天氣,只能是客戶端向服務器發出請求,服務器返回查詢結果。HTTP 協議做不到服務器主動向客戶端推送信息。

這種單向請求的特點,註定瞭如果服務器有連續的狀態變化,客戶端要獲知就非常麻煩。我們只能使用"輪詢":每隔一段時候,就發出一個詢問,瞭解服務器有沒有新的信息。最典型的場景就是聊天室。

輪詢的效率低,非常浪費資源(因爲必須不停連接,或者 HTTP 連接始終打開)。因此,工程師們一直在思考,有沒有更好的方法。WebSocket 就是這樣發明的。

順便膜拜一下 五行代碼實現一個最簡單的聊天工具  ,該git hub項目竟然雖然只有5行代碼,但是start已經18K.

#!/bin/bash

# Copyright 2013 Jeroen Janssens
# All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.

# Run a simple chat server: websocketd --devconsole --port 8080 ./chat.sh
#
# Please note that this example requires GNU tail, which is not the default
# tail on OS X. Even though this script properly escapes the variables,
# please keep in mind that it is in general a bad idea to read
# untrusted data into variables and pass this onto the command line.

echo "Please enter your name:"; read USER
echo "[$(date)] ${USER} joined the chat" >> chat.log
echo "[$(date)] Welcome to the chat ${USER}!"
tail -n 0 -f chat.log --pid=$$ | grep --line-buffered -v "] ${USER}>" &
while read MSG; do echo "[$(date)] ${USER}> ${MSG}" >> chat.log; done

websocket 實戰

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章