TCP client
package mainimport ("fmt""net""os"
)func main() {//Actively connect to the server conn, err:= net.Dial("tcp", "127.0.0.1:8000")if err != nil {fmt.Println("Dial err = ", err)return}//Close the connection defer conn.Close ()//Input content from the keyboard and send content to the server go func() {//Slice cache buf_key:= make([]byte, 1024)for {num, err:= os.Stdin.Read (buf_key)if err != nil {fmt.Println("os.Stdin.Read err = ", err)return}//Send data conn.Write(buf_key[:num])fmt.Println ("client send buf = ", string(buf_key[:num]))}}()//Receive the data buf replied by the server:= make([]byte, 1024)for {num, err := conn.Read(buf)if err != nil { //When the read fails, the main coroutine exits directly fmt.Println("Read err = ", err )return}fmt.Println("client recv buf = ", string(buf[:num]))}
}
TCP server
package mainimport ("fmt""net""strings"
)func HandleConn(conn net.Conn) {//Automatically close the connection defer conn.Close()//Get the customer End network address information addr:= conn.RemoteAddr().String()fmt.Println(addr, "connect success!")buf:= make([]byte, 2*1024)for {/ /Read user data num, err:= conn.Read(buf)if err != nil {fmt.Println("Read err = ", err)return}fmt.Printf(" [%s]:read buf = %s", addr, string(buf[:num]))//TCP knowledge: The newline character in the UNIX system generated after pressing the RETURN key, sent by the server to the client Yes: Carriage return and line feed characters (CR/LF),i.e. "\r\n",Their function is to move the cursor back to the left and move to the next line//Based on the above explanation: echo There will be 2 more bytes (this method is only a temporary solution) if string(buf[:num-2]) == "exit" {fmt.Println(addr, " close!")return}/ /Convert the data to uppercase and send it to the user conn.Write([]byte(strings.ToUpper(string(buf[:num]))))}
}func main() {//1. Listen, err := net.Listen("tcp", "127.0.0.1:8000")if err != nil {fmt.Println("Listen err = ", err)return}// Close defer listen.Close()//Receive multiple users for {conn, err:= listen.Accept()if err != nil {fmt.Println("Accept err = ", err)return}//Process the user's request (new coroutine)go HandleConn(conn)}
}