Reading data from a TCP connection
One of the most common scenarios in any application is the client interacting with the server. TCP is one of the most widely used protocols for this interaction. Go provides a convenient way to read incoming connection data through bufio
implementing buffered Input/Output
, which we will be covering in this recipe.
Getting ready…
As we have already created a TCP server in our previous recipe, we will update it to read data from incoming connections.
How to do it…
In this recipe, we are going to update the main()
method to call a handleRequest
method passing the connection object to read and print data on the server console. Perform the following steps:
- Create
tcp-server-read-data.go
and copy the following content:
package main import ( "bufio" "fmt" "log" "net" ) const ( CONN_HOST = "localhost" CONN_PORT = "8080" CONN_TYPE = "tcp" ) func main() { listener, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT) if err != nil { log.Fatal("Error starting tcp server : ", err) } defer listener.Close() log.Println("Listening on " + CONN_HOST + ":" + CONN_PORT) for { conn, err := listener.Accept() if err != nil { log.Fatal("Error accepting: ", err.Error()) } go handleRequest(conn) } } func handleRequest(conn net.Conn) { message, err := bufio.NewReader(conn).ReadString('\n') if err != nil { fmt.Println("Error reading:", err.Error()) } fmt.Print("Message Received from the client: ", string(message)) conn.Close() }
- Run the program with the following command:
$ go run tcp-server-read-data.go
How it works…
Once we run the program, the TCP server will start locally listening on port 8080
. Executing an echo
command from the command line as follows will send a message to the TCP server:
$ echo -n "Hello to TCP server\n" | nc localhost 8080
This apparently logs it to a server console, as shown in the following screenshot:

Let’s understand the change we introduced in this recipe:
- First, we called
handleRequest
from themain()
method using thego
keyword, which means we are invoking a function in a Goroutine, as follows:
func main() { ... go handleRequest(conn) ... }
- Next, we defined the
handleRequest
function, which reads an incoming connection into the buffer until the first occurrence of\n
and prints the message on the console. If there are any errors in reading the message then it prints the error message along with the error object and finally closes the connection, as follows:
func handleRequest(conn net.Conn) { message, err := bufio.NewReader(conn).ReadString('\n') if err != nil { fmt.Println("Error reading:", err.Error()) } fmt.Print("Message Received: ", string(message)) conn.Close() }