Handling multiple connections using goroutines

This commit is contained in:
raul 2024-03-10 09:07:08 +01:00
parent a4a5594096
commit a41033f150
1 changed files with 15 additions and 8 deletions

View File

@ -4,24 +4,30 @@ 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 {
conn, err := ln.Accept()
catchErr(err)
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) {
@ -29,6 +35,7 @@ func catchErr(err error) (errHappened bool) {
if err != nil {
errHappened = true
fmt.Println(err)
os.Exit(2)
}
return errHappened
}