---
title: "Websocket 查看实时日志"
date: 2019-10-30T11:43:23+08:00
lastmod: 2019-10-30T11:43:23+08:00
tags: ["websocket"]
categories: ["web"]
---

## 操作系统
- CentOS7

## 下载 websocketd
- [websocketd-0.3.0-linux_amd64.zip](https://github.com/joewalnes/websocketd/releases/download/v0.3.0/websocketd-0.3.0-linux_amd64.zip)

## 安装 nc 命令
```bash
yum install nmap-ncat
```

## 创建监听脚本
```bash
cat > cmd.sh <<-END
##!/bin/bash
pkill -x nc
while :; do
    nc -nkl 10088
    sleep 1
done
END
```

## 创建 log.html
```html
<!DOCTYPE html>
<html>
<head>
    <style>
        body{
            background-color: #0e1012;color: #ffffff;
        }
        *{
            margin: 0; padding: 0;
        }
        #msg{
            overflow:auto; border:2px solid #303030; color:#ffffff; background-color: #2b2b2b; font-size: 13px; position: absolute; left: 8px; right: 8px; bottom: 8px; top: 40px; word-break:
break-all;
        }
        #log{
            position: fixed; top: 0; left: 0; width: 100%; height: 40px; text-align: left; margin: 4px 0 0 8px;
        }
        #log b{
            font-size: 26px;
        }
        #msgBtn{
            padding: 5px 10px; border: none; background: #777; float: right; margin: 0 16px 0 0;
        }
    </style>
</head>
<body>
    <div id="log"><span><b>实时日志</b></span><button id="msgBtn" type="button">清空</button></div>
    <div id="msg"><ul class="list"></ul></div>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            if (!window.WebSocket) {
                if (window.MozWebSocket) {
                    window.WebSocket = window.MozWebSocket;
                } else {
                    $('#msg').append("<p>你的浏览器不支持websocket</p>");
                }
            }
            var ws = new WebSocket('ws://221.7.197.100:8008/websocket/');
            ws.onopen = function(evt) {
                $('.list').append('<li>websocket连接成功</li>');
            }
            ws.onmessage = function(evt) {
                $('.list').append('<li>' + evt.data + '</li>');
                setTimeout(function(){$('#msg').scrollTop($('.list').height()-$('#msg').height());}, 100)
            }
            $("#msgBtn").click(function(){
                $(".list").html("");
            })
        });
    </script>
</body>
</html>
```

## 文件部署位置
```
websocketd/
├── [-rwxr-xr-x]  cmd.sh
├── [drwxr-xr-x]  websocket
│   └── [-rw-r--r--]  log.html
└── [-rwxr-xr-x]  websocketd
```

## 启动 websocketd
```bash
cd websocketd
./websocketd --port=8008 --staticdir=. ./cmd.sh
```

## 在浏览器中打开日志浏览页面
- http://{websocket-server}:8008/websocket/log.html

## 在其他应用服务器，传输实时日志
```bash
tail -f /tomcat/logs/catalina.out | nc -n {websocket-server} 10088
```

## 关闭实时日志
- 在目标服务器中 kill nc
    ```bash
    pkill -x nc
    ```
- 在 websocket server 中 kill nc
    ```bash
    pkill -x nc
    ```
- 直接刷新浏览器的日志浏览页面

