服务端的代码
package main import ( "fmt" "net" ) func main () { fmt.Println("start server...") //Listen来创建服务端 ln, err := net.Listen("tcp", ":10010") if err != nil { fmt.Println("listen failed, err:", err) return } for { conn, err := ln.Accept() if err != nil { fmt.Println("accept failed, err:", err) continue } //开启新的gouroutine 去处理请求 //每个请求开启一个goroutine go process(conn) } } func process (conn net.Conn) { defer conn.Close() for { buf := make([]byte, 512) _, err := conn.Read(buf) if err != nil { fmt.Println("read failed, err:", err) return } fmt.Println("read:", string(buf)) } }
客户端代码:
//客户端程序 package main import ( "fmt" "os" "strings" "bufio" "net" ) func main () { conn, err := net.Dial("tcp", "localhost:10010") if err != nil { fmt.Println("Erroring dialing", err.Error()) return } defer conn.Close() inputReader := bufio.NewReader(os.Stdin) for{ input, _ := inputReader.ReadString(\'\n\') trimedinput := strings.Trim(input, "\r\n") if trimedinput == "Q" { return } _, err := conn.Write([]byte(trimedinput)) if err != nil { return } } }
先编译,然后执行,开启服务端
然后新开一个窗口,作为客户端请求
请发表评论