Writing TCP clients
A TCP client connects to a TCP server that is listening on a port of some host. Once the connection is established, communication is bidirectional. In other words, the distinction between a server and a client is based on how the connection is established. When we say “server,” we mean the program that waits listening to a port, and when we say “client,” we mean the program that connects (“dials”) a port on a host that is being listened on by a server. Once the connection is established, both sides send and receive data asynchronously. TCP guarantees that the messages will be received in the order they are sent, and that the messages will not be lost, but there are no guarantees on when a message will be received by the other side.
How to do it...
- The client side has to know the server address and port. This should be provided by the environment (command line, configuration, etc.).
- Use
net.Dial
to create a connection to the server:conn, err := net.Dial("tcp", addr) if err != nil { // Handle error }
- Use the returned
net.Conn
object to send data to the server, or to receive data from the server:// Send a line of text text := []byte("Hello echo server!") conn.Write(text) // Read the response response := make([]byte, len(text)) conn.Read(response) fmt.Println(string(response))
- Close the connection when done:
conn.Close()
Here is the complete program:
var address = flag.String("a", ":8008", "Server address") func main() { flag.Parse() conn, err := net.Dial("tcp", *address) if err != nil { panic(err) } // Send a line of text text := []byte("Hello echo server!") conn.Write(text) // Read the response response := make([]byte, len(text)) conn.Read(response) fmt.Println(string(response)) conn.Close() }
This example demonstrates a request-response type of interaction with the server. This is not necessarily always the case. A network connection provides both an io.Writer
and an io.Reader
interface, and they can be used concurrently.