From a41033f150f2c176c2a18803bcb9f55cd36667f0 Mon Sep 17 00:00:00 2001 From: raul Date: Sun, 10 Mar 2024 09:07:08 +0100 Subject: [PATCH] Handling multiple connections using goroutines --- sockets/main.go | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/sockets/main.go b/sockets/main.go index 163d189..df4a669 100644 --- a/sockets/main.go +++ b/sockets/main.go @@ -4,31 +4,38 @@ import ( "bufio" "fmt" "net" + "os" "strings" ) func main() { ln, err := net.Listen("tcp", ":1302") catchErr(err) - fmt.Println("Listening on port 1302") - - conn, err := ln.Accept() - catchErr(err) + fmt.Printf("Listening on port 1302...\n") for { - message, err := bufio.NewReader(conn).ReadString('\n') + conn, err := ln.Accept() catchErr(err) - fmt.Printf("Message received: %v", string(message)) - newMsg := strings.ToUpper(message) - conn.Write([]byte(newMsg + "\n")) + go handleConn(conn) } } +func handleConn(conn net.Conn) { + defer conn.Close() + + message, err := bufio.NewReader(conn).ReadString('\n') + catchErr(err) + fmt.Printf("Message received: %v", string(message)) + newMsg := strings.ToUpper(message) + conn.Write([]byte(newMsg + "\n")) +} + func catchErr(err error) (errHappened bool) { errHappened = false if err != nil { errHappened = true fmt.Println(err) + os.Exit(2) } return errHappened }