2023-12-19 20:49:11 +01:00
|
|
|
package network
|
2023-12-12 20:59:54 +01:00
|
|
|
|
|
|
|
|
import (
|
2023-12-16 20:52:05 +01:00
|
|
|
"cimeyclust.com/steel/pkg/cmd"
|
2023-12-17 00:43:24 +01:00
|
|
|
"context"
|
2023-12-12 20:59:54 +01:00
|
|
|
"fmt"
|
2023-12-23 20:05:00 +01:00
|
|
|
"github.com/sandertv/go-raknet"
|
2023-12-12 20:59:54 +01:00
|
|
|
"net"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// Start Starts the TCP server on the specified address.
|
2023-12-17 00:43:24 +01:00
|
|
|
func Run(baseCtx context.Context, addr string) {
|
|
|
|
|
ctx, cancel := context.WithCancel(baseCtx)
|
|
|
|
|
defer cancel()
|
2023-12-12 20:59:54 +01:00
|
|
|
|
|
|
|
|
// Start listening on the specified address
|
2023-12-23 20:05:00 +01:00
|
|
|
listener, err := raknet.Listen(addr)
|
2023-12-12 20:59:54 +01:00
|
|
|
if err != nil {
|
2023-12-18 21:06:17 +01:00
|
|
|
cmd.Logger.Error(fmt.Sprintf("Error starting UDP server: %v", err))
|
2023-12-17 00:43:24 +01:00
|
|
|
return
|
2023-12-12 20:59:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Close the listener when the application closes.
|
2023-12-17 00:43:24 +01:00
|
|
|
defer listener.Close()
|
2023-12-12 20:59:54 +01:00
|
|
|
|
2023-12-16 20:52:05 +01:00
|
|
|
cmd.Logger.Info(fmt.Sprintf("Listening on %s", addr))
|
|
|
|
|
|
2023-12-12 20:59:54 +01:00
|
|
|
// Listen for an incoming connection in a goroutine.
|
|
|
|
|
go func() {
|
2023-12-17 00:43:24 +01:00
|
|
|
go func() {
|
2023-12-17 01:03:49 +01:00
|
|
|
// Waiting for the context to be done
|
2023-12-17 00:43:24 +01:00
|
|
|
<-ctx.Done()
|
2023-12-17 01:03:49 +01:00
|
|
|
|
|
|
|
|
// Waiting for the listener to be closed, so the port is safely released
|
2023-12-17 00:43:24 +01:00
|
|
|
listener.Close()
|
|
|
|
|
}()
|
2023-12-12 20:59:54 +01:00
|
|
|
for {
|
|
|
|
|
conn, err := listener.Accept()
|
|
|
|
|
if err != nil {
|
|
|
|
|
select {
|
2023-12-17 00:43:24 +01:00
|
|
|
case <-ctx.Done():
|
|
|
|
|
return
|
2023-12-12 20:59:54 +01:00
|
|
|
default:
|
2023-12-16 20:52:05 +01:00
|
|
|
cmd.Logger.Error(fmt.Sprintf("Error while accepting conn: %v", err))
|
2023-12-12 20:59:54 +01:00
|
|
|
}
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Handle connections in a new goroutine.
|
|
|
|
|
go handleRequest(conn)
|
|
|
|
|
}
|
|
|
|
|
}()
|
|
|
|
|
|
2023-12-17 00:43:24 +01:00
|
|
|
// Wait for all components to finish
|
|
|
|
|
<-ctx.Done()
|
2023-12-12 20:59:54 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// handleRequest handles incoming requests.
|
|
|
|
|
func handleRequest(conn net.Conn) {
|
|
|
|
|
// Close the connection when you're done with it.
|
|
|
|
|
defer conn.Close()
|
|
|
|
|
|
2023-12-19 20:49:11 +01:00
|
|
|
cmd.Logger.Info("Tet")
|
2023-12-18 21:06:17 +01:00
|
|
|
b := make([]byte, 1024*1024*4)
|
2023-12-19 20:49:11 +01:00
|
|
|
n, _ := conn.Read(b)
|
|
|
|
|
cmd.Logger.Info(fmt.Sprintf("Current n: %v", n))
|
2023-12-18 21:06:17 +01:00
|
|
|
cmd.Logger.Info(fmt.Sprintf("Received: %v", b))
|
2023-12-12 20:59:54 +01:00
|
|
|
}
|