conn, err := net.Dial("tcp", "localhost:8080") if err != nil { log.Fatal(err) } _, err := conn.Write([]byte("Hello, server!")) if err != nil { log.Fatal(err) } buf := make([]byte, 1024) n, err := conn.Read(buf) if err != nil { log.Fatal(err) } fmt.Println(string(buf[:n])) conn.Close()
listener, err := net.Listen("tcp", "localhost:8080") if err != nil { log.Fatal(err) } defer listener.Close() for { conn, err := listener.Accept() if err != nil { log.Fatal(err) } go func(c net.Conn) { defer c.Close() buf := make([]byte, 1024) for { n, err := c.Read(buf) if err != nil { return } _, err = c.Write(buf[:n]) if err != nil { return } } }(conn) }This code snippet demonstrates how to create a simple TCP server that echoes back any data that it receives. The net.Listen() function creates a new TCP listener that waits for incoming connections on the specified port. We then use the listener.Accept() method to wait for an incoming connection. Once we have a connection, we launch a new goroutine to handle it. In this goroutine, we read data from the client using conn.Read() and then write it back to the client using conn.Write(). The loop continues indefinitely, so the server will continue to handle incoming connections until it is manually shut down. Package library: "net" package in standard Go library.