Skip to content

Commit

Permalink
Add exit command
Browse files Browse the repository at this point in the history
  • Loading branch information
ah-naf committed Aug 31, 2024
1 parent 53ba258 commit c16f21e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 5 deletions.
7 changes: 4 additions & 3 deletions client/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,14 @@ func listenForMessages(conn net.Conn) {
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
log.Fatalln("Server disconnected.")
}

// Clear the current input prompt
fmt.Print("\r\033[K") // This clears the line

if err != nil {
os.Exit(0)
}

// Print the new message
fmt.Print(FgGreen + Bold + message + Reset)

Expand Down
12 changes: 10 additions & 2 deletions server/internals/chatserver/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func (cs *ChatServer) HandleConnection(conn net.Conn) {

mode = strings.TrimSpace(mode)
log.Println("User", username, "entered mode:", mode)

switch mode {
case "global":
cs.handleGlobalChat(conn, reader, username)
Expand All @@ -75,7 +76,14 @@ func (cs *ChatServer) handleGlobalChat(conn net.Conn, reader *bufio.Reader, user
cs.RemoveClient(conn, username)
return
}
formattedMessage := utils.FormatChatMessage(username, strings.TrimSpace(message))
cs.BroadcastMessage(formattedMessage, conn)

trimmedMessage := strings.TrimSpace(message)
if strings.HasPrefix(trimmedMessage, "/") {
// Handle command
cs.HandleCommand(conn, trimmedMessage[1:])
} else {
formattedMessage := utils.FormatChatMessage(username, strings.TrimSpace(message))
cs.BroadcastMessage(formattedMessage, conn)
}
}
}
20 changes: 20 additions & 0 deletions server/internals/chatserver/commands.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package chatserver

import (
"net"
"strings"
)

// HandleCommand processes commands for user
func(cs *ChatServer) HandleCommand(conn net.Conn, command string) {
command = strings.TrimSpace(command)
args := strings.Split(command, " ")

switch args[0] {
case "exit":
cs.RemoveClient(conn, cs.globalClients[conn])
conn.Write([]byte("You have exited the server.\n"))
conn.Close()

}
}

0 comments on commit c16f21e

Please sign in to comment.