欢迎光临
我们一直在努力

go语言学习例子No.28–页面实时获取系统信息5

按照逗比VPS监控的样子仿照做了一个

效果是这样的

知识点

按socket分为了客户端和服务端

index.html部分

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <title>Go语言与ajax示例</title>

    <!-- Bootstrap core CSS -->
<link href="assets/dist/css/bootstrap.min.css" rel="stylesheet">
    
  </head>
  <body>
  <div class="container themed-container">
      <header class="d-flex justify-content-center py-3">
        <p class="h2">系统信息</p>
      </header>
        <table class="table table-sm table-bordered" style="text-align: center;">
          <thead>
          <tr>
            <th scope="col">节点名</th>
            <th scope="col">在线时间</th>
            <th scope="col">网络 ↓|↑</th>
            <th scope="col">流量 ↓|↑</th>
            <th scope="col">处理器</th>
            <th scope="col">内存</th>
            <th scope="col">硬盘</th>
          </tr>
          </thead>
          <tbody>
          <tr data-bs-toggle="collapse" data-bs-target="#tr1" aria-expanded="true">
            <th scope="row">RackNerd2.5G</th>
            <td id="day">8天</td>
            <td id="net">1K | 2K</td>
            <td id="speed">1G | 2G</td>
            <td><div class="progress">
              <div class="progress-bar bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="cpu">0%</div></div></td>
            <td><div class="progress">
              <div class="progress-bar bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="mem">0%</div></div></td>
            <td><div class="progress">
              <div class="progress-bar bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" id="disk">0%</div></div></td>
          </tr>
          <tr>
            <td colspan="16"><div id="tr1" class="collapse">
              显示额外信息
            </div></td>
            
          </tr>


          </tbody>
        </table>
    </article>
  </div>

    <script src="assets/dist/js/bootstrap.bundle.min.js"></script>
  <script src="assets/dist/js/jquery-3.6.0.min.js"></script>
    <script src="assets/dist/js/loli.js"></script>


  </body>
</html>

js部分

$(function (){
    setInterval(myajax, 2000);
    function myajax(){
        $.get('/ajax',function(data,status){
            if (status == 'success') {
                cpuclass = data.Cpuused+"%"
                memclass = data.Memused+"%"
                diskclass = data.Diskused+"%"
                $('#cpu').css("width",cpuclass)
                $('#cpu').text(data.Cpuused+"%")
                $('#mem').css("width",memclass)
                $('#mem').text(data.Memused+"%")
                $('#disk').css("width",diskclass)
                $('#disk').text(data.Diskused+"%")
                $('#net').text(data.Netsend+"G | "+data.Netrecv+"G")
                $('#speed').text(data.Netdown+" | "+data.Netup)
                $('#day').text(data.Uptime+"天")
                $('#tr1').text("硬盘: "+data.Diskfree+"G/"+ data.Disktotal+'G | 内存: '+data.Memavailable+"G/"+ data.Memtotal+"G | Swap: "+data.Swapfree+"G/"+data.Swaptotal+"G")
            }
        });
    };
});

server服务端

package main

import (
	"fmt"
	"net"
	"net/http"
	"text/template"
)

type Consys struct {
	data string
	c  net.Conn

}
var info string

func index(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("index.html") //找模板
	t.Execute(w, nil)                         //执行模板
}
func ajax(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-type", "application/json;charset=utf-8")
	fmt.Fprintln(w,info)
}
func main() {
	go startserver()//开个协程,要不然会跟http的监听有冲突
	http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("assets"))))
	http.HandleFunc("/", index)      //函数也是一种变量
	http.HandleFunc("/ajax", ajax) //函数也是一种变量
	http.ListenAndServe(":8082", nil)
}



func startserver(){
	addr, _ := net.ResolveTCPAddr("tcp4", "localhost:8899")
	lis, _ := net.ListenTCP("tcp4", addr)
	fmt.Println("服务器已启动")

	for {//通过gorountine,每个客户端分配一个独立协程。
		conn, _ := lis.Accept()
		go handleConn(conn)
	}

	fmt.Println("服务器结束")
}

func handleConn(conn net.Conn){
	defer conn.Close()
	b := make([]byte, 256)
	for{
		count, err := conn.Read(b)
		if err != nil {//这里判断一下err,如果断开就跳出循环,关闭当前连接
			fmt.Println(err.Error())
			break
		}
		info = string(b[:count])
	}
}

client部分

package main
import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"
	net2 "net"

	"github.com/shirou/gopsutil/cpu"
	"github.com/shirou/gopsutil/disk"
	"github.com/shirou/gopsutil/mem"
	"github.com/shirou/gopsutil/net"
	"github.com/shirou/gopsutil/host"
)

type Sys struct {
	Cpuused      int
	Memused      int
	Memavailable float64
	Swaptotal	float64
	Swapfree	float64
	Memtotal     float64
	Disktotal    float64
	Diskfree     float64
	Diskused     int
	Netsend      float64
	Netrecv      float64
	Netup        string
	Netdown      string
	Uptime      int
}
func main(){
	//服务器端ip和端口
	conn, _ := net2.Dial("tcp", "localhost:8899")
	//向服务端发送数据
	s:=Sys{}
	c := make(chan []byte,2)//设置2个缓存,这样取了一个就会马上放进去一个
	go func() {
		for{
			s = getstatus()
			d, _ := json.Marshal(s)
			c<-d
		}
	}()
	for{
		conn.Write(<-c)
	}

	////关闭连接
	conn.Close()
}
func toG(i uint64) float64 {
	return float64(i) / 1024 / 1024 / 1024
}
func toKB(i uint64) float64 {
	return float64(i) / 1024
}
func toMB(i uint64) float64 {
	return float64(i) / 1024 / 1024
}
func Decimal(value float64) float64 {
	value, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", value), 64)
	return value
}

func getNetSpeed() (string, string) {
	// 读取所有网卡网速
	Net, _ := net.IOCounters(true)
	// 定义网速保存变量
	var rx, tx uint64
	// 循环网络信息
	for _, nv := range Net {
		// 去除多余信息
		if "eth0" == nv.Name {
			// 加上网速信息
			rx += nv.BytesRecv
			tx += nv.BytesSent
		}
	}
	// 暂停一秒
	time.Sleep(time.Second)
	// 重新读取网络信息
	Net, _ = net.IOCounters(true)
	// 网络信息保存变量
	var rx2, tx2 uint64
	// 循环网络信息
	for _, nv := range Net {
		// 去除多余信息
		if "eth0" == nv.Name {
			// 加上网速信息
			rx2 += nv.BytesRecv
			tx2 += nv.BytesSent
		}
	}
	// 两次相减
	if toKB(rx2-rx) > 1024 || toKB(tx2-tx) > 1024 {
		down:= strconv.FormatFloat(toMB(rx2 - rx),'f',2,64)+"MB/S"
		up:= strconv.FormatFloat(toMB(tx2 - tx),'f',2,64)+"MB/S"
		return down, up
	} else {
		down:= strconv.FormatFloat(toKB(rx2 - rx),'f',2,64)+"KB/S"
		up:= strconv.FormatFloat(toKB(tx2 - tx),'f',2,64)+"KB/S"
		return down, up
	}

}
func getstatus() Sys {
	s := Sys{}
	m, _ := mem.VirtualMemory()
	c, _ := cpu.Percent(time.Second, false)
	d, _ := disk.Usage("/")
	n, _ := net.IOCounters(true)
	swap,_:=mem.SwapMemory()
	s.Netsend = Decimal(toG(n[1].BytesSent))
	s.Netrecv = Decimal(toG(n[1].BytesRecv))
	s.Diskused = int(d.UsedPercent)
	s.Diskfree = Decimal(toG(d.Free))
	s.Disktotal = Decimal(toG(d.Total))
	s.Memused = int(m.UsedPercent)
	s.Memtotal = Decimal(toG(m.Total))
	s.Memavailable = Decimal(toG(m.Available))
	s.Cpuused = int(c[0])
	s.Netdown, s.Netup = getNetSpeed()
	s.Uptime = int(getUptime()/60/60/24)
	s.Swaptotal=Decimal(toG(swap.Total))
	s.Swapfree=Decimal(toG((swap.Free)))
	return s
}
func getUptime() uint64 {//获取的是秒数
	up, err := host.BootTime()
	if nil != err {
		return 0
	}
	return uint64(time.Now().Unix()) - up
}

现在只有一个客户端,下次实时多个客户端连接怎么传递数据到页面

 收藏 (0) 打赏

您可以选择一种方式赞助本站

支付宝扫一扫赞助

微信钱包扫描赞助

未经允许不得转载:家里蹲的狐狸 » go语言学习例子No.28–页面实时获取系统信息5

分享到: 生成海报
avatar

热门文章

  • 评论 抢沙发

    • QQ号
    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址

    登录

    忘记密码 ?

    切换登录

    注册

    我们将发送一封验证邮件至你的邮箱, 请正确填写以完成账号注册和激活