-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
96 lines (85 loc) · 1.86 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
87
88
89
90
91
92
93
94
95
96
package allnet
import (
"fmt"
"io"
"net"
"net/http"
"github.com/noxyal/allsoc"
"golang.org/x/net/websocket"
)
// server stores a ptr to the Server struct
var server *Server
// onConnect is a callback called on each new connection
var onConnect func(*allsoc.Socket)
// Server example fields: Server{":9090", ":8080", "public/fileserver"}
type Server struct {
TCPPort, HTTPPort, StaticPath string
OnConnect func(*allsoc.Socket)
}
// StartServer starts server and listens. Default settings: Server{":9090", ":8080", "public/fileserver"}
func StartServer(s *Server) {
if s == nil {
s = &Server{}
}
if s.TCPPort == "" {
s.TCPPort = ":9090"
}
if s.HTTPPort == "" {
s.HTTPPort = ":8080"
}
if s.StaticPath == "" {
s.StaticPath = "public/fileserver"
}
if s.OnConnect == nil {
s.OnConnect = newConn
}
allsoc.SetupAllsoc()
server = s
onConnect = s.OnConnect
go netListen(s.TCPPort)
http.Handle("/ws", websocket.Handler(wsHandler))
http.Handle("/", http.FileServer(http.Dir(s.StaticPath)))
err := http.ListenAndServe(s.HTTPPort, nil)
if err != nil {
fmt.Println("HTTP Error:", err.Error())
}
}
func netListen(port string) {
l, err := net.Listen("tcp", port)
if err != nil {
fmt.Println("TCP Error:", err.Error())
return
}
for {
c, err := l.Accept()
if err != nil {
fmt.Println("TCP Error:", err.Error())
} else {
go socketHandler(c)
}
}
}
func wsHandler(ws *websocket.Conn) {
socketHandler(ws)
}
func socketHandler(iorw io.ReadWriter) {
rw := &iorw
soc := allsoc.NewSocket(rw)
soc.Join("")
onConnect(soc)
}
// newConn is the default OnConnect. It is an echo and broadcast server.
func newConn(soc *allsoc.Socket) {
fmt.Println("a user connected!")
msg := make([]byte, 32*1024)
for {
n, err := soc.Read(msg)
if err != nil {
return
}
if n > 0 {
soc.Broadcast("", msg[0:n])
soc.Write(msg[0:n])
}
}
}