From 544369cb9f800f8aa49a15dc6b8be33ff874e97d Mon Sep 17 00:00:00 2001 From: raul Date: Fri, 29 Mar 2024 09:36:03 +0100 Subject: [PATCH] Fixed server crashing whenever a user disconnected Instead of trying to let Cobra handle the possible errors produced in client input through bufio.NewReader(conn), I'm handling them manually by returning the function if there's an error detected, therefore severing the goroutine and letting the main server run normally --- cmd/server.go | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/cmd/server.go b/cmd/server.go index e26e971..bb4e162 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -6,6 +6,7 @@ package cmd import ( "bufio" "fmt" + //"log" "net" "strings" "time" @@ -58,8 +59,8 @@ func server(cmd *cobra.Command) { cobra.CheckErr(err) fmt.Printf("Listening on port %v...\n", lport) for { - conn, err := ln.Accept() - cobra.CheckErr(err) + conn, _ := ln.Accept() + //cobra.CheckErr(err) go handleConn(conn) } @@ -80,13 +81,18 @@ func handleConn(conn net.Conn) { fmt.Print(final_message) conn.Write([]byte("What's your name?\nName: ")) name, err := bufio.NewReader(conn).ReadString('\n') - cobra.CheckErr(err) + if err != nil { + return + } var NewUser = new(chatter) NewUser.Username = strings.TrimRight(name, "\n") NewUser.IP = IP for { message, err := bufio.NewReader(conn).ReadString('\n') - cobra.CheckErr(err) + if err != nil { + fmt.Printf(NewUser.Username + " disconnected!\n") + return + } fmt.Print("{" + NewUser.IP + "} " + NewUser.Username + ": " + message) conn.Write([]byte(message)) }