专业的编程技术博客社区

网站首页 > 博客文章 正文

为什么要用webSocket?(为什么要用前锁后塞)

baijin 2024-10-15 08:34:11 博客文章 8 ℃ 0 评论

最近在接触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


原文链接:https://blog.csdn.net/MyySophia/article/details/106219310


Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表