[PD1] Generic networking server and client implemented

This commit is contained in:
Afonso Franco 2024-04-17 14:09:42 +01:00
parent 8553e1674e
commit 278b8e1a73
Signed by: afonso
SSH key fingerprint: SHA256:aiLbdlPwXKJS5wMnghdtod0SPy8imZjlVvCyUX9DJNk
4 changed files with 114 additions and 38 deletions

View file

@ -1,30 +1,43 @@
package server
import (
_ "PD1/internal/utils/cryptoUtils"
_ "PD1/internal/utils/networking"
"PD1/internal/protocol"
"PD1/internal/utils/networking"
"encoding/json"
"fmt"
"net"
)
func clientHandler(conn net.Conn) {
func clientHandler(connection networking.Connection[protocol.Packet]) {
defer connection.Conn.Close()
jd := json.NewDecoder(connection.Conn)
for {
var pac protocol.Packet
jd.Decode(&pac)
switch pac.Flag {
case protocol.ReqPK:
fmt.Println("ReqPK")
case protocol.ReqAllMsg:
fmt.Println("ReqAllMsg")
case protocol.ReqMsg:
fmt.Println("ReqMsg")
case protocol.SubmitMsg:
fmt.Println("SubmitMsh")
}
}
}
func Run(port int) {
ip, err := net.ResolveTCPAddr("tcp", ":8080")
if err != nil {
panic("Server could not bind to address")
}
listener, err := net.ListenTCP("tcp", ip)
if err != nil {
panic("Server could not listen on address")
}
server := networking.NewServer[protocol.Packet](port)
go server.ListenLoop()
for {
conn, err := listener.Accept()
if err!=nil{
panic("Server could not accept connection")
}
go clientHandler(conn)
//Receive connection via channel
conn := <-server.C
//Launch client handler via clientHandler
go clientHandler(conn)
}
}