功能:客户端持续写入数据,直到输入exit退出,服务端读取数据并打印
注意:server和client目录在同一层级
服务端
server/main
package mainimport ("fmt""net"
)func main() {listen, err := net.Listen("tcp", "0.0.0.0:8080")if err != nil {fmt.Printf("err: %v\n", err)return}fmt.Println("server is listening")defer listen.Close()for {conn, err2 := listen.Accept()if err2 != nil {fmt.Printf("err2: %v\n", err2)return}fmt.Printf("server: %v\n", conn.LocalAddr())go readData(conn)}
}func readData(conn net.Conn) {defer conn.Close()buf := make([]byte, 1024)for {n, err := conn.Read(buf)if err != nil {fmt.Printf("err: %v\n", err)return}fmt.Println("读取了", n, "字节数据")fmt.Println("buf:", string(buf[:n]))}
}
客户端
client/main
go开启协程,数据写入结束向管道输入信号,主线程获取信号,退出。否则主线程运行结束会直接退出
package mainimport ("bufio""fmt""net""os""strings"
)var exitchan chan boolfunc main() {fmt.Println("client is wating to connect")conn, err := net.Dial("tcp", "192.168.0.1:8080")if err != nil {fmt.Printf("err: %v\n", err)return}go writeData(conn)if <-exitchan {fmt.Print("client exit")}
}func writeData(conn net.Conn) {defer conn.Close()reader := bufio.NewReader(os.Stdin)len := 0for {line, err := reader.ReadString('\n')if err != nil {return}line = strings.Trim(line, "\r\n")len, err = conn.Write([]byte(line))if err != nil {return}if line == "exit" {break}fmt.Println("写入", len, "字节数据")}fmt.Println("client:", conn.RemoteAddr())exitchan <- true
}