I have setup a server to wait for a TCP connection and read an input from the user:
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal(err)
}
server, err := net.Listen("tcp", ":"+os.Getenv("PORT"))
if err != nil {
log.Fatal(err)
}
log.Println("HTTP Server Listening on port :", os.Getenv("PORT"))
defer server.Close()
for {
conn, err := server.Accept()
if err != nil {
log.Fatal(err)
}
go handleConn(conn)
}
}
The issue I am having is in my handleConn
function. I want to kick off reading the input into a goroutine because there will be additional data processing. However, when I connect to my server (nc localhost 9000
), my connection gets dropped immediately.
func handleConn(conn net.Conn) {
defer conn.Close()
io.WriteString(conn, "Enter a transaction:")
scanner := bufio.NewScanner(conn)
go func() {
for scanner.Scan() {
log.Println("User entered: ")
log.Println(scanner.Text())
}
}()
}
I see the message Enter a transaction:
, but I am not able to input anything because my connection is immediately terminated and I am kicked back to my bash terminal. What am I doing wrong here?
Edit: I am following this tutorial - https://github.com/mycoralhealth/blockchain-tutorial/blob/master/networking/main.go.
I have tried moving scanner.Scan()
outside the goroutine and this works, but the code example here has it within the goroutine and his example works. Why is this the case?
Since you're spawning a goroutine in your handleConn
func, it doesn't need to wait for anything to return, so the deferred conn.Close()
runs and closes the connection. You might need to run scanner.Scan()
out of the goroutine so that it blocks waiting for input.