最近在写服务的监控,因项目比较老最早的开发人员早已不在,想获取服务的同时在线人数,通过telnet命令是可以获取,今天想用Go实现类telnet命令的获取方式。
package main
import (
"net"
"os"
"fmt"
"io"
"strings"
"strconv"
)
var (
hostPost string = "127.0.0.1:1900"
)
func main() {
conn, err := net.Dial("tcp", hostPost)
if err != nil {
fmt.Printf("connent failed: %v", err)
return
}
defer conn.Close()
_, err = conn.Write([]byte("stats\r\n"))
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
return
}
buf := make([]byte, 4096)
n, err := conn.Read(buf)
if err != nil {
fmt.Println(err)
return
}
s := string(buf[0:n])
for _,m := range strings.Split(s,"\n") {
if m != "" {
line := strings.Split(m ,":")
if line[0] == "total_connections" {
v := strings.Replace(line[1],"\r","",-1)
x, err := strconv.ParseFloat(v, 64)
if err != nil {
fmt.Println("format err: ",err)
}
fmt.Println(x)
}
}
}
}