switch to golang wrapper for enet
This commit is contained in:
parent
4420b4e061
commit
ee3b8d3490
10 changed files with 188 additions and 194 deletions
76
backend/main.go
Normal file
76
backend/main.go
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"log/slog"
|
||||
"os"
|
||||
|
||||
enet "github.com/codecat/go-enet"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
port := uint16(8095)
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
slog.SetDefault(logger)
|
||||
|
||||
// Initialize enet
|
||||
slog.Info("Initializing E-Net Server", "port", port)
|
||||
enet.Initialize()
|
||||
|
||||
// Create a host listening on 0.0.0.0:8095
|
||||
host, err := enet.NewHost(enet.NewListenAddress(port), 32, 1, 0, 0)
|
||||
if err != nil {
|
||||
slog.Error("Couldn't create host", "error", err)
|
||||
return
|
||||
}
|
||||
slog.Info("Server started", "port", port)
|
||||
|
||||
// The event loop
|
||||
for true {
|
||||
// Wait until the next event
|
||||
ev := host.Service(1000)
|
||||
|
||||
// Do nothing if we didn't get any event
|
||||
if ev.GetType() == enet.EventNone {
|
||||
continue
|
||||
}
|
||||
|
||||
switch ev.GetType() {
|
||||
case enet.EventConnect: // A new peer has connected
|
||||
slog.Info("New peer connected", "address", ev.GetPeer().GetAddress())
|
||||
|
||||
case enet.EventDisconnect: // A connected peer has disconnected
|
||||
slog.Info("Peer disconnected", "address", ev.GetPeer().GetAddress())
|
||||
|
||||
case enet.EventReceive: // A peer sent us some data
|
||||
// Get the packet
|
||||
packet := ev.GetPacket()
|
||||
|
||||
// We must destroy the packet when we're done with it
|
||||
defer packet.Destroy()
|
||||
|
||||
// Get the bytes in the packet
|
||||
packetBytes := packet.GetData()
|
||||
|
||||
// Respond "pong" to "ping"
|
||||
if string(packetBytes) == "ping" {
|
||||
ev.GetPeer().SendString("pong", ev.GetChannelID(), enet.PacketFlagReliable)
|
||||
continue
|
||||
}
|
||||
|
||||
// Disconnect the peer if they say "bye"
|
||||
if string(packetBytes) == "bye" {
|
||||
slog.Info("Peer sent bye, disconnecting")
|
||||
ev.GetPeer().Disconnect(0)
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Destroy the host when we're done with it
|
||||
host.Destroy()
|
||||
|
||||
// Uninitialize enet
|
||||
enet.Deinitialize()
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue