From 6da487bc86a0925902c91df14f6ab414cd167883 Mon Sep 17 00:00:00 2001 From: raul Date: Fri, 29 Mar 2024 14:57:02 +0100 Subject: [PATCH] Create testing branch and start channels --- cmd/server.go | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/cmd/server.go b/cmd/server.go index 20c695f..b76c154 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -58,10 +58,14 @@ func server(cmd *cobra.Command) { ln, err := net.Listen("tcp", ":"+lport) cobra.CheckErr(err) fmt.Printf("Listening on port %v...\n", lport) + messageChan := make(chan string) + // TODO: get channels properly working + //receivingChannel := make(chan string) + //sendingChannelº := make(chan string) for { conn, err := ln.Accept() cobra.CheckErr(err) - go handleConn(conn) + go handleConn(conn, messageChan) } } @@ -71,14 +75,22 @@ type chatter struct { IP string } -func handleConn(conn net.Conn) { - +func handleConn(conn net.Conn, ch chan string) { defer conn.Close() + var otherMessage string + + go func() { + for { + otherMessage = <-ch + conn.Write([]byte(otherMessage)) + } + }() + IP := getIP(conn) t := time.Now() date := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) - final_message := fmt.Sprintf("[%v] Received connection from %v!\n", date, IP) - fmt.Print(final_message) + final_message_connect := fmt.Sprintf("[%v] Received connection from %v!\n", date, IP) + fmt.Print(final_message_connect) conn.Write([]byte("What's your name?\nName: ")) name, err := bufio.NewReader(conn).ReadString('\n') if err != nil { @@ -93,8 +105,10 @@ func handleConn(conn net.Conn) { fmt.Printf(NewUser.Username + " disconnected!\n") return } - fmt.Print("{" + NewUser.IP + "} " + NewUser.Username + ": " + message) - conn.Write([]byte(message)) + finalMessage := fmt.Sprint("{" + NewUser.IP + "} " + NewUser.Username + ": " + message) + fmt.Print(finalMessage) + ch <- finalMessage + //conn.Write([]byte(message)) } }