32_Go基础(TCP通信)
Server:
package main import ( "bufio" "fmt" "net" ) func worker(conn net.Conn) { defer conn.Close() for { reader := bufio.NewReader(conn) var buf [128]byte n, err := reader.Read(buf[:]) // 读取数据 if err != nil { fmt.Println("Read msg from client failed ,err: ", err) break } resStr := string(buf[:n]) fmt.Println("收到Client的数据:", resStr) conn.Write([]byte(resStr)) // 发送数据 } } func main() { listen, err := net.Listen("tcp", "127.0.0.1:9000") if err != nil { fmt.Println("Listen failed,err: ", err) return } for { conn, err := listen.Accept() // 建立链接 if err != nil { fmt.Println("Accept failed, err: ", err) } go worker(conn) // 启动一个 goroutine 处理 } }
Client:
package main import ( "bufio" "fmt" "net" "os" "strings" ) func main() { conn, err := net.Dial("tcp", "127.0.0.1:9000") if err != nil { fmt.Println("err: ", err) } defer conn.Close() cReader := bufio.NewReader(os.Stdin) for { input, _ := cReader.ReadString('\n') info := strings.Trim(input, "\r\n") if strings.ToUpper(info) == "Q" { // 如果输入q/Q,就退出 return } _, err := conn.Write([]byte(info)) // 发送数据 if err != nil { buf := [512]byte{} n, err := conn.Read(buf[:]) if err != nil { fmt.Println("Client receive msg err: ", err) return } fmt.Println(string(buf[:n])) } } }