Steel/pkg/network/network.go

69 lines
1.5 KiB
Go
Raw Normal View History

2023-12-19 20:49:11 +01:00
package network
import (
2023-12-16 20:52:05 +01:00
"cimeyclust.com/steel/pkg/cmd"
"context"
"fmt"
2023-12-23 20:05:00 +01:00
"github.com/sandertv/go-raknet"
"net"
)
// Start Starts the TCP server on the specified address.
func Run(baseCtx context.Context, addr string) {
ctx, cancel := context.WithCancel(baseCtx)
defer cancel()
// Start listening on the specified address
2023-12-23 20:05:00 +01:00
listener, err := raknet.Listen(addr)
if err != nil {
2023-12-18 21:06:17 +01:00
cmd.Logger.Error(fmt.Sprintf("Error starting UDP server: %v", err))
return
}
// Close the listener when the application closes.
defer listener.Close()
2023-12-16 20:52:05 +01:00
cmd.Logger.Info(fmt.Sprintf("Listening on %s", addr))
// Listen for an incoming connection in a goroutine.
go func() {
go func() {
2023-12-17 01:03:49 +01:00
// Waiting for the context to be done
<-ctx.Done()
2023-12-17 01:03:49 +01:00
// Waiting for the listener to be closed, so the port is safely released
listener.Close()
}()
for {
conn, err := listener.Accept()
if err != nil {
select {
case <-ctx.Done():
return
default:
2023-12-16 20:52:05 +01:00
cmd.Logger.Error(fmt.Sprintf("Error while accepting conn: %v", err))
}
continue
}
// Handle connections in a new goroutine.
go handleRequest(conn)
}
}()
// Wait for all components to finish
<-ctx.Done()
}
// 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))
}