-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
86 lines (77 loc) · 1.79 KB
/
server.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package main
import (
"fmt"
"net"
protos "github.com/Pixelgaffer/dico-proto"
"github.com/golang/protobuf/proto"
log "github.com/Sirupsen/logrus"
)
func handleClient(conn net.Conn) {
defer conn.Close()
buff, err := protos.ReadPacket(conn)
checkErr(err)
log.WithField("buff", buff).Debug("Decoding Handshake")
hs, err := protos.DecodeUnknownMessage(buff)
checkErr(err)
connection := &Connection{conn: &conn}
connection.init(*hs.(*protos.Handshake))
connections.Lock()
connections.all = append(connections.all, connection)
connections.Unlock()
gcConnections()
go connection.handle()
go func() {
for {
buff, err := protos.ReadPacket(conn)
if err != nil {
log.WithField("addr", conn.RemoteAddr()).Warn(err)
connection.kill()
return
}
log.WithField("buff", buff).Debug("Decoding Packet")
msg, err := protos.DecodeUnknownMessage(buff)
if err != nil {
log.WithField("addr", conn.RemoteAddr()).Warn(err)
connection.kill()
return
}
connection.recv <- msg
}
}()
for {
select {
case <-connection.doneCh:
return
case msg := <-connection.send:
log.WithFields(log.Fields{
"addr": conn.RemoteAddr(),
"message": msg,
}).Debug("sending data")
wrapped := protos.WrapMessage(msg)
data, err := proto.Marshal(wrapped)
checkErr(err)
err = protos.WritePacket(conn, data)
if err != nil {
log.WithField("addr", conn.RemoteAddr()).Warn(err)
connection.kill()
}
}
}
}
func checkErr(e error) {
if e != nil {
log.Warn(e)
}
}
func listen(port int) {
pstr := fmt.Sprintf(":%d", port)
log.Info("Listening on " + pstr + "...")
ln, err := net.Listen("tcp", pstr)
checkErr(err)
for {
conn, err := ln.Accept()
log.WithField("addr", conn.RemoteAddr()).Info("new connection")
checkErr(err)
go handleClient(conn)
}
}