mini-chat/cmd/server.go

121 lines
2.8 KiB
Go
Raw Normal View History

2024-03-29 09:04:20 +01:00
/*
Copyright © 2024 Raul
*/
package cmd
import (
"bufio"
"fmt"
//"log"
2024-03-29 09:04:20 +01:00
"net"
"strings"
"time"
//"os"
"github.com/spf13/cobra"
)
// serverCmd represents the server command
var serverCmd = &cobra.Command{
Use: "server",
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
server(cmd)
},
}
func init() {
rootCmd.AddCommand(serverCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// serverCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// serverCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
serverCmd.Flags().String("port", "1302", "Port to listen on")
}
func server(cmd *cobra.Command) {
var lport string
port, _ := cmd.Flags().GetString("port")
if port != "" {
lport = port
} else {
lport = "1302"
}
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)
2024-03-29 09:04:20 +01:00
for {
conn, err := ln.Accept()
cobra.CheckErr(err)
go handleConn(conn, messageChan)
2024-03-29 09:04:20 +01:00
}
}
type chatter struct {
Username string
IP string
}
func handleConn(conn net.Conn, ch chan string) {
2024-03-29 09:04:20 +01:00
defer conn.Close()
var otherMessage string
go func() {
for {
otherMessage = <-ch
conn.Write([]byte(otherMessage))
}
}()
2024-03-29 09:04:20 +01:00
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_connect := fmt.Sprintf("[%v] Received connection from %v!\n", date, IP)
fmt.Print(final_message_connect)
2024-03-29 09:04:20 +01:00
conn.Write([]byte("What's your name?\nName: "))
name, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
return
}
2024-03-29 09:04:20 +01:00
var NewUser = new(chatter)
NewUser.Username = strings.TrimRight(name, "\n")
NewUser.IP = IP
for {
message, err := bufio.NewReader(conn).ReadString('\n')
if err != nil {
fmt.Printf(NewUser.Username + " disconnected!\n")
return
}
finalMessage := fmt.Sprint("{" + NewUser.IP + "} " + NewUser.Username + ": " + message)
fmt.Print(finalMessage)
ch <- finalMessage
//conn.Write([]byte(message))
2024-03-29 09:04:20 +01:00
}
}
func getIP(conn net.Conn) (IP string) {
if addr, ok := conn.RemoteAddr().(*net.TCPAddr); ok {
IP = fmt.Sprintf("%v", addr)
}
return IP
}