golang-exercises/chat-tests/cmd/serverFunc.go

151 lines
3.2 KiB
Go
Raw Permalink Normal View History

2024-04-25 10:30:10 +02:00
/*
Copyright © 2024 Raul <raul@bulgariu.xyz>
*/
package cmd
import (
2024-04-23 08:30:36 +02:00
"bufio"
"fmt"
"log"
"net"
2024-04-23 08:30:36 +02:00
"strings"
)
var (
2024-04-23 07:59:38 +02:00
listenPort string = "1302"
)
2024-04-23 07:59:38 +02:00
type Creator interface {
CreateUser()
}
type User struct {
Username string
IP string
}
2024-04-23 07:59:38 +02:00
func (u User) CreateUser(usr string, ip string) User {
u.Username = usr
u.IP = ip
return u
}
func Server() {
2024-04-23 07:59:38 +02:00
ln, err := net.Listen("tcp", ":"+listenPort)
if err != nil {
log.Fatalf("Error happened trying to listen on port: %v\n", err)
}
defer ln.Close()
fmt.Printf("Listening on port %v...\n", listenPort)
for {
conn, err := ln.Accept()
2024-04-23 07:59:38 +02:00
if err != nil {
log.Fatalf("Error happened trying to accept connection: %v\n", err)
}
2024-04-25 10:30:10 +02:00
chatChan := make(chan string, 10)
listenerList = append(listenerList, chatChan)
go handleConn(conn, chatChan)
}
}
2024-04-25 10:30:10 +02:00
var listenerList []chan string
func getUsername(conn net.Conn) (s string, err error) {
conn.Write([]byte("What's your name?\nChoice: "))
2024-04-23 08:30:36 +02:00
name, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
return "", err
2024-04-23 08:30:36 +02:00
}
trimmedName := strings.TrimRight(name, "\n")
return trimmedName, nil
2024-04-23 08:30:36 +02:00
}
func getUserInput(conn net.Conn) (s string, err error) {
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
return "", err
}
return message, nil
}
2024-04-25 10:30:10 +02:00
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) {
2024-04-23 07:59:38 +02:00
defer conn.Close()
2024-04-25 10:30:10 +02:00
go receiveMessageServer(conn, chatChan)
//////////////////////////////////
// Get user information
//////////////////////////////////
userName, err := getUsername(conn)
if err != nil {
log.Printf("Error occurred getting username: %v\n", err)
2024-04-25 10:30:10 +02:00
//removeFromList(chatChan)
return
}
userIP := getIP(conn)
//////////////////////////////////
2024-04-23 07:59:38 +02:00
newUserTemplate := new(User)
newUser := newUserTemplate.CreateUser(userName, userIP)
joinMessage := fmt.Sprintf("%v has joined the chat!", newUser.Username)
fmt.Println(joinMessage)
2024-04-25 10:30:10 +02:00
//conn.Write([]byte(joinMessage))
sendMessage(joinMessage)
//////////////////////////////////
for {
message, err := getUserInput(conn)
if err != nil {
2024-04-25 10:30:10 +02:00
quitMessage := fmt.Sprintf("%v has disconnected!", newUser.Username)
fmt.Println(quitMessage)
sendMessage(quitMessage)
//removeFromList(chatChan)
// if _, err := conn.Write([]byte(quitMessage)); err != nil {
// log.Printf("Error happened sending disconnect message: %v", err)
// }
return
}
finalMessage := fmt.Sprintf("[%v] %v: %v", newUser.IP, newUser.Username, strings.TrimRight(message, "\n"))
fmt.Printf("%v\n", finalMessage)
2024-04-25 10:30:10 +02:00
sendMessage(finalMessage)
//chatChan <- finalMessage
// if _, err := conn.Write([]byte(finalMessage)); err != nil {
// log.Printf("Error happened sending message: %v", err)
// }
}
//////////////////////////////////
}
2024-04-25 10:30:10 +02:00
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))
}
}
}
2024-04-23 07:59:38 +02:00
func getIP(conn net.Conn) (IP string) {
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
IP = fmt.Sprintf("%v", addr.IP)
}
2024-04-23 07:59:38 +02:00
return IP
}