-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
68 lines (53 loc) · 1.48 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package main
import (
"github.com/codecat/go-enet"
"github.com/codecat/go-libs/log"
)
func main() {
print("Hello world!")
// Initialize enet
enet.Initialize()
// Create a host listening on 0.0.0.0:8095
host, err := enet.NewHost(enet.NewListenAddress(8095), 32, 1, 0, 0)
if err != nil {
log.Error("Couldn't create host: %s", err.Error())
return
}
// The event loop
for true {
// Wait until the next event
ev := host.Service(0)
// 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
log.Info("New peer connected: %s", ev.GetPeer().GetAddress())
case enet.EventDisconnect: // A connected peer has disconnected
log.Info("Peer disconnected: %s", 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" {
log.Info("Bye!")
ev.GetPeer().Disconnect(0)
continue
}
}
}
// Destroy the host when we're done with it
host.Destroy()
// Uninitialize enet
enet.Deinitialize()
}