A go echo server using go channel, but no reply from the server

Issue

I am trying to use go channel and goroutine to write an echo server, but there is no reply from the server. The following server listens on port 9090, and create a channel ch to receive connection acceptances, then it pass to handleClient to handle the connection details. Is the following code wrong? It has no errors when under go build.

package main

import (
    "fmt"
    "net"
)

const (
    CONN_HOST = "localhost"
    CONN_PORT = "9090"
    CONN_TYPE = "tcp"
)

func main() {
    listen, err := net.Listen(CONN_TYPE, CONN_HOST + ":" + CONN_PORT)
    if err != nil {
        fmt.Println("Error listening: ", err.Error())
        return
    }

    ch := make(chan net.Conn)
    go func() {
        for {
            conn, err := listen.Accept()
            if err != nil {
                fmt.Println("Error Accept: ", err.Error())
                return
            }
            ch <- conn
        }
    }()
    go handleClient(ch)
}

func handleClient(connChan <-chan net.Conn) {
    var tcpConn net.Conn
    // fmt.Println("Accepted new client: ", connChan.RemoteAddr().String())
    for {
        tcpConn = <-connChan
        go Serve(tcpConn)
    }
}

func Serve(conn net.Conn) {
  // handle the connection
}

Solution

Just change your main a bit:

ch := make(chan net.Conn)
go handleClient(ch)

for {
    conn, err := listen.Accept()
    if err != nil {
        fmt.Println("Error Accept: ", err.Error())
        return
    }
    ch <- conn
}

The for loop is the server’s main loop and will run forever if you do not exit the server somewhere else.

Answered By – ikrabbe

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.