go实现tcp通讯
1.客户端代码
package main import ( "bufio" "fmt" "net" "os" "strings" ) func main(){ conn,err:= net.Dial("tcp","127.0.0.1:8890") if err != nil { fmt.Println("is erro") } reader:= bufio.NewReader(os.Stdin) fmt.Printf("%v,\n","请写入内容") for { text,_:=reader.ReadString('\n') text = strings.TrimSpace(text) if text == "exit" { break } conn.Write([]byte(text)) } conn.Close() }
2.服务端代码
package main import ( "bufio" "fmt" "io" "net" ) func process(conn net.Conn){ defer conn.Close() var buf[1024]byte reader:=bufio.NewReader(conn) for { n,err:=reader.Read(buf[:]) if err == io.EOF { break } if err != nil { return } recvStr:= string(buf[:n]) fmt.Printf("收到的数据为:%v\n",recvStr) } } func main(){ listener,err:=net.Listen("tcp","127.0.0.1:8890") if err != nil { fmt.Println("start server is erros") return } for { conn,_:= listener.Accept() go process(conn) } defer listener.Close() }