This repository has been archived by the owner on Apr 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
74 lines (59 loc) · 1.57 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
package gominet
import (
"fmt"
"log"
"net"
"errors"
"github.com/justblender/gominet/protocol"
"github.com/justblender/gominet/protocol/packet"
)
var NoHandlerException = errors.New("No packet handler has been specified")
type Server struct {
host string
port int
listener net.Listener
handler Handler
}
type Handler func(*protocol.Connection, packet.Holder) error
func NewServer(host string, port int, handler Handler) *Server {
return &Server{host: host, port: port, handler: handler}
}
func (server *Server) SetHandler(handler Handler) {
server.handler = handler
}
func (server *Server) ListenAndServe() (err error) {
if server.handler == nil {
return NoHandlerException
}
server.listener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", server.host, server.port))
if err != nil {
return
}
for {
client, err := server.listener.Accept()
if err != nil {
log.Println("Error occurred while accepting a connection: " + err.Error())
continue
}
// log.Println("Incoming connection from " + client.RemoteAddr().String())
go server.handleConnection(protocol.NewConnection(client))
}
}
func (server *Server) handleConnection(conn *protocol.Connection) {
defer conn.Close()
for {
holder, err := conn.Next()
if err != nil {
if err == protocol.UnknownPacketType {
continue
}
// Not sure what to do about this one..
// log.Println("Error occurred while reading packet: " + err.Error())
break
}
if err = server.handler(conn, holder); err != nil {
log.Println("Error occurred while handling packet: " + err.Error())
break
}
}
}