Making Golang TCP server concurrent

The reason you see this behavior is the fact that your main method exits even though your go routine is still running. Make sure to block the main method to achieve what you are trying to achieve.

May be add something like this in the main:

c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
<-c // This will block until you manually exists with CRl-C

Also you can bring back your defer


When you run function using go func() syntax, you are executing a new goroutine without blocking the main one. However, the program will exit when the main goroutine finishes, so in short, you need to block the main goroutine for as long as you want your child goroutines to execute.

I often find myself checking how similar problems are solved in go standard library. For example, Server.Serve() from http package does something similar. Here is the extracted version (shortened, follow the link to see full version):

func (srv *Server) Serve(l net.Listener) error {
   defer l.Close()

   ctx := context.Background() 
   for {
      rw, e := l.Accept()
      if e != nil {
        select {
        case <-srv.getDoneChan():
            return ErrServerClosed
        default:
        }
        if ne, ok := e.(net.Error); ok && ne.Temporary() {
            // handle the error
        }
        return e
      }
      c := srv.newConn(rw)
      c.setState(c.rwc, StateNew) // before Serve can return
      go c.serve(ctx)
   }
}

To stop the above function, we could close the listener (e.g. via interrupt signal), which in turn would generate an error on Accept(). The above implementation checks whether serv.GetDoneChan() channel returns a value as an indicator that the error is expected and the server is closed.


Your main function is returning immediately after accepting a new connection, so your program exits before the connection can be handled. Since you probably also want to receive more than one single connection (or else there would be no concurrency), you should put this in a for loop.

You are also creating a new buffered reader in each iteration of the for loop, which would discard any buffered data. You need to do that outside the for loop, which I demonstrate here by creating a new bufio.Scanner which is a simpler way to read newline delimited text.

import (
    "bufio"
    "fmt"
    "log"
    "net"
    "strings"
)

func handleConnection(conn net.Conn) {
    defer conn.Close()
    scanner := bufio.NewScanner(conn)
    for scanner.Scan() {
        message := scanner.Text()
        fmt.Println("Message Received:", message)
        newMessage := strings.ToUpper(message)
        conn.Write([]byte(newMessage + "\n"))
    }

    if err := scanner.Err(); err != nil {
        fmt.Println("error:", err)
    }
}

func main() {
    ln, err := net.Listen("tcp", "127.0.0.1:8081")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Accept connection on port")

    for {
        conn, err := ln.Accept()
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println("Calling handleConnection")
        go handleConnection(conn)
    }
}