服务器端程序
package main
import (
"fmt"
"log"
"net"
)
func handleConnection(conn net.Conn) {
defer conn.Close()
for {
var buf = make([]byte, 1024)
n, err := conn.Read(buf)
if err != nil {
log.Fatal("conn read error: ",err)
break
}
fmt.Printf("%s", string(buf[:n]))
}
}
func main() {
ln, err := net.Listen("tcp", ":6010")
if err != nil {
panic(err)
}
for {
conn, err := ln.Accept()
if err != nil {
log.Fatal("get client connection error: ", err)
}
go handleConnection(conn)
}
}
客户端程序
package main
import (
"net"
"os"
"log"
"bufio"
)
func main() {
conn, err := net.Dial("tcp", ":6010")
if err != nil {
panic(err)
}
inputReader := bufio.NewReader(os.Stdin)
// 读取输入字符,发送到服务器
for {
input, err := inputReader.ReadString('\n')
if err != nil {
log.Fatal("ReadString error: ", err)
}
conn.Write([]byte(input))
}
}
读取追加日志向服务器发送
package main
import (
"net"
"github.com/hpcloud/tail"
"fmt"
)
func main() {
conn, err := net.Dial("tcp", ":6010")
if err != nil {
panic(err)
}
defer conn.Close()
// 当前文件夹下output.txt会不断追加日志
t, _ := tail.TailFile("./output.txt", tail.Config{Follow: true, Location: &tail.SeekInfo{0, 2}, Logger:tail.DiscardingLogger})
for line := range t.Lines {
fmt.Println(line.Text)
conn.Write([]byte(line.Text))
}
}