From f14b18142f6e6989e5119fccdc3033fa1d07def3 Mon Sep 17 00:00:00 2001 From: Robert Date: Sat, 8 Feb 2025 21:41:49 -0500 Subject: [PATCH] @USER tagged private messages --- chat_server.go | 46 ++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/chat_server.go b/chat_server.go index 0047b2b..7fbea18 100644 --- a/chat_server.go +++ b/chat_server.go @@ -10,7 +10,7 @@ import ( "net" "sync" "time" - + "strings" "gopkg.in/yaml.v2" "os" "github.com/yang3yen/xxtea-go/xxtea" @@ -93,6 +93,16 @@ func (um *UserManagerTCP) GetUserListTCP() string { } return userList } +func (um *UserManagerTCP) UserMatchTCP(user string, encrypted []byte, sender net.Conn) { + um.mutex.Lock() + defer um.mutex.Unlock() + for clientCon, client := range um.clients { + if user == client.username { + clientCon.Write(encrypted) + } + } +} + func (um *UserManagerUDP) GetUserListUDP() string { um.mutex.Lock() defer um.mutex.Unlock() @@ -253,6 +263,20 @@ func sayServer(text string) ([]byte, error) { return encrypted, nil } +func parseInput(input string) (username string, message string) { + // Check if the input starts with '@' + if strings.HasPrefix(input, "@") { + // Trim the '@' and split by spaces + parts := strings.SplitN(input[1:], " ", 2) + username = parts[0] + if len(parts) > 1 { + message = parts[1] + return username, message + } + } + return "", "" +} + func handleTCPClient(conn net.Conn) { defer conn.Close() @@ -296,9 +320,14 @@ func handleTCPClient(conn net.Conn) { // Handle the 'users' command userList := userManagerTCP.GetUserListTCP() sayTCP(conn, "User's Online: "+userList) - } else { - // Broadcast the message to all other clients - broadcastTCP(decrypted, conn) + } else { + privateUser, text := parseInput(message) + if privateUser != "" && text != "" { + privateTCP(privateUser, decrypted, conn) + } else { + // Broadcast the message to all other clients + broadcastTCP(decrypted, conn) + } } } @@ -382,6 +411,15 @@ func startUDPServer() error { } } +func privateTCP(user string, data []byte, sender net.Conn) { + encrypted, err := encryptor.Encrypt(data) + if err != nil { + fmt.Printf("Encryption error: %v\n", err) + return + } + userManagerTCP.UserMatchTCP(user, encrypted, sender) +} + func broadcastTCP(data []byte, sender net.Conn) { encrypted, err := encryptor.Encrypt(data) if err != nil {