Finish cleaner chat server

This commit is contained in:
raul 2024-04-25 10:30:10 +02:00
parent 11f600fd8f
commit 3c56a83b0f
2 changed files with 52 additions and 12 deletions

View File

@ -17,7 +17,7 @@ var serverCmd = &cobra.Command{
using a proper interface this time, not using netcat. using a proper interface this time, not using netcat.
Example: Example:
./tiny-chat server --port 1337`, ./mini-chat server --port 1337`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
if err := setServerParameters(cmd); err != nil { if err := setServerParameters(cmd); err != nil {

View File

@ -1,3 +1,7 @@
/*
Copyright © 2024 Raul <raul@bulgariu.xyz>
*/
package cmd package cmd
import ( import (
@ -39,10 +43,14 @@ func Server() {
if err != nil { if err != nil {
log.Fatalf("Error happened trying to accept connection: %v\n", err) log.Fatalf("Error happened trying to accept connection: %v\n", err)
} }
go handleConn(conn) chatChan := make(chan string, 10)
listenerList = append(listenerList, chatChan)
go handleConn(conn, chatChan)
} }
} }
var listenerList []chan string
func getUsername(conn net.Conn) (s string, err error) { func getUsername(conn net.Conn) (s string, err error) {
conn.Write([]byte("What's your name?\nChoice: ")) conn.Write([]byte("What's your name?\nChoice: "))
name, err := bufio.NewReader(conn).ReadString('\n') name, err := bufio.NewReader(conn).ReadString('\n')
@ -62,15 +70,26 @@ func getUserInput(conn net.Conn) (s string, err error) {
return message, nil return message, nil
} }
func handleConn(conn net.Conn) { func removeFromList(chatChan chan string) {
for i, v := range listenerList {
if v == chatChan {
listenerList = append(listenerList[:i], listenerList[:i+1]...)
}
}
}
func handleConn(conn net.Conn, chatChan chan string) {
defer conn.Close() defer conn.Close()
go receiveMessageServer(conn, chatChan)
////////////////////////////////// //////////////////////////////////
// Get user information // Get user information
////////////////////////////////// //////////////////////////////////
userName, err := getUsername(conn) userName, err := getUsername(conn)
if err != nil { if err != nil {
log.Printf("Error occurred getting username: %v\n", err) log.Printf("Error occurred getting username: %v\n", err)
//removeFromList(chatChan)
return return
} }
userIP := getIP(conn) userIP := getIP(conn)
@ -80,28 +99,49 @@ func handleConn(conn net.Conn) {
newUser := newUserTemplate.CreateUser(userName, userIP) newUser := newUserTemplate.CreateUser(userName, userIP)
joinMessage := fmt.Sprintf("%v has joined the chat!", newUser.Username) joinMessage := fmt.Sprintf("%v has joined the chat!", newUser.Username)
fmt.Println(joinMessage) fmt.Println(joinMessage)
conn.Write([]byte(joinMessage)) //conn.Write([]byte(joinMessage))
sendMessage(joinMessage)
////////////////////////////////// //////////////////////////////////
for { for {
message, err := getUserInput(conn) message, err := getUserInput(conn)
if err != nil { if err != nil {
quitMessage := fmt.Sprintf("%v has disconnected!\n", newUser.Username) quitMessage := fmt.Sprintf("%v has disconnected!", newUser.Username)
fmt.Print(quitMessage) fmt.Println(quitMessage)
if _, err := conn.Write([]byte(quitMessage)); err != nil { sendMessage(quitMessage)
log.Printf("Error happened sending disconnect message: %v", err) //removeFromList(chatChan)
} // if _, err := conn.Write([]byte(quitMessage)); err != nil {
// log.Printf("Error happened sending disconnect message: %v", err)
// }
return return
} }
finalMessage := fmt.Sprintf("[%v] %v: %v", newUser.IP, newUser.Username, strings.TrimRight(message, "\n")) finalMessage := fmt.Sprintf("[%v] %v: %v", newUser.IP, newUser.Username, strings.TrimRight(message, "\n"))
fmt.Printf("%v\n", finalMessage) fmt.Printf("%v\n", finalMessage)
if _, err := conn.Write([]byte(finalMessage)); err != nil { sendMessage(finalMessage)
log.Printf("Error happened sending message: %v", err)
} //chatChan <- finalMessage
// if _, err := conn.Write([]byte(finalMessage)); err != nil {
// log.Printf("Error happened sending message: %v", err)
// }
} }
////////////////////////////////// //////////////////////////////////
} }
func sendMessage(msg string) {
for _, ch := range listenerList {
ch <- msg
}
}
func receiveMessageServer(conn net.Conn, chatChan chan string) {
for {
select {
case message := <-chatChan:
conn.Write([]byte(message))
}
}
}
func getIP(conn net.Conn) (IP string) { func getIP(conn net.Conn) (IP string) {
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok { if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
IP = fmt.Sprintf("%v", addr.IP) IP = fmt.Sprintf("%v", addr.IP)