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
This commit is contained in:
raul 2024-03-29 09:36:03 +01:00
parent 2ff99a284b
commit 544369cb9f
1 changed files with 10 additions and 4 deletions

View File

@ -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))
}