O'Reilly logo

Go Web Development Cookbook by Arpit Aggarwal

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it…

In this recipe, we are going to create a simple TCP server that will accept a connection on localhost:8080. Perform the following steps:

  1. Create tcp-server.go and copy the following content:
package mainimport (  "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())    }    log.Println(conn)  }}
  1. Run the program with the following command:
$ go run tcp-server.go

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required