Create testing branch and start channels

This commit is contained in:
raul 2024-03-29 14:57:02 +01:00
parent cd009e8ee6
commit 6da487bc86
1 changed files with 21 additions and 7 deletions

View File

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