2024-04-22 08:21:59 +02:00
|
|
|
package cmd
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"net"
|
2024-04-23 07:59:38 +02:00
|
|
|
"time"
|
2024-04-22 08:21:59 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2024-04-23 07:59:38 +02:00
|
|
|
listenPort string = "1302"
|
2024-04-22 08:21:59 +02:00
|
|
|
)
|
|
|
|
|
2024-04-23 07:59:38 +02:00
|
|
|
type Creator interface {
|
|
|
|
CreateUser()
|
2024-04-22 08:21:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type User struct {
|
|
|
|
Username string
|
|
|
|
IP string
|
|
|
|
}
|
|
|
|
|
2024-04-23 07:59:38 +02:00
|
|
|
type Message struct {
|
|
|
|
Contents string
|
|
|
|
Date time.Time
|
|
|
|
}
|
|
|
|
|
|
|
|
func (u User) CreateUser(usr string, ip string) User {
|
|
|
|
u.Username = usr
|
|
|
|
u.IP = ip
|
|
|
|
return u
|
2024-04-22 08:21:59 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
2024-04-22 08:21:59 +02:00
|
|
|
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-22 08:21:59 +02:00
|
|
|
go handleConn(conn)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func getUserInput() {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleConn(conn net.Conn) {
|
2024-04-23 07:59:38 +02:00
|
|
|
defer conn.Close()
|
|
|
|
newUserTemplate := new(User)
|
|
|
|
newUser := newUserTemplate.CreateUser("Tom", getIP(conn))
|
|
|
|
fmt.Printf("Received connection from %v at %v\n", newUser.Username, newUser.IP)
|
2024-04-22 08:21:59 +02:00
|
|
|
fmt.Fprintln(conn, "Hello buddy!")
|
|
|
|
}
|
|
|
|
|
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-22 08:21:59 +02:00
|
|
|
}
|
2024-04-23 07:59:38 +02:00
|
|
|
|
|
|
|
return IP
|
2024-04-22 08:21:59 +02:00
|
|
|
}
|