-
Notifications
You must be signed in to change notification settings - Fork 33
/
server.go
225 lines (187 loc) · 5.77 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/*
* Glue - Robust Go and Javascript Socket Library
* Copyright (C) 2015 Roland Singer <roland.singer[at]desertbit.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Package glue - Robust Go and Javascript Socket Library.
// This library is thread-safe.
package glue
import (
"fmt"
"net"
"net/http"
"sync"
"time"
"github.com/desertbit/glue/backend"
)
//####################//
//### Public Types ###//
//####################//
// OnNewSocketFunc is an event function.
type OnNewSocketFunc func(s *Socket)
//###################//
//### Server Type ###//
//###################//
// A Server represents a glue server which handles incoming socket connections.
type Server struct {
bs *backend.Server
options *Options
block bool
blockMutex sync.Mutex
onNewSocket OnNewSocketFunc
sockets map[string]*Socket // A map holding all active current sockets.
socketsMutex sync.Mutex
}
// NewServer creates a new glue server instance.
// One variadic arguments specifies the server options.
func NewServer(o ...Options) *Server {
// Get or create the options.
var options *Options
if len(o) > 0 {
options = &o[0]
} else {
options = &Options{}
}
// Set the default option values for unset values.
options.SetDefaults()
// Create a new backend server.
bs := backend.NewServer(len(options.HTTPHandleURL), options.EnableCORS, options.CheckOrigin)
// Create a new server value.
s := &Server{
bs: bs,
options: options,
onNewSocket: func(*Socket) {}, // Initialize with dummy function to remove nil check.
sockets: make(map[string]*Socket),
}
// Set the backend server event function.
bs.OnNewSocketConnection(s.handleOnNewSocketConnection)
return s
}
// Block new incomming connections.
func (s *Server) Block(b bool) {
s.blockMutex.Lock()
defer s.blockMutex.Unlock()
s.block = b
}
// IsBlocked returns a boolean whenever new incoming connections should be blocked.
func (s *Server) IsBlocked() bool {
s.blockMutex.Lock()
defer s.blockMutex.Unlock()
return s.block
}
// OnNewSocket sets the event function which is
// triggered if a new socket connection was made.
// The event function must not block! As soon as the event function
// returns, the socket is added to the active sockets map.
func (s *Server) OnNewSocket(f OnNewSocketFunc) {
s.onNewSocket = f
}
// GetSocket obtains a socket by its ID.
// Returns nil if not found.
func (s *Server) GetSocket(id string) *Socket {
// Lock the mutex.
s.socketsMutex.Lock()
defer s.socketsMutex.Unlock()
// Obtain the socket.
socket, ok := s.sockets[id]
if !ok {
return nil
}
return socket
}
// Sockets returns a list of all current connected sockets.
// Hint: Sockets are added to the active sockets list before the OnNewSocket
// event function is called.
// Use the IsInitialized flag to determind if a socket is not ready yet...
func (s *Server) Sockets() []*Socket {
// Lock the mutex.
s.socketsMutex.Lock()
defer s.socketsMutex.Unlock()
// Create the slice.
list := make([]*Socket, len(s.sockets))
// Add all sockets from the map.
i := 0
for _, s := range s.sockets {
list[i] = s
i++
}
return list
}
// Release this package. This will block all new incomming socket connections
// and close all current connected sockets.
func (s *Server) Release() {
// Block all new incomming socket connections.
s.Block(true)
// Wait for a little moment, so new incomming sockets are added
// to the sockets active list.
time.Sleep(200 * time.Millisecond)
// Close all current connected sockets.
sockets := s.Sockets()
for _, s := range sockets {
s.Close()
}
}
// Run starts the server and listens for incoming socket connections.
// This is a blocking method.
func (s *Server) Run() error {
// Skip if set to none.
if s.options.HTTPSocketType != HTTPSocketTypeNone {
// Set the base glue HTTP handler.
http.Handle(s.options.HTTPHandleURL, s)
// Start the http server.
if s.options.HTTPSocketType == HTTPSocketTypeUnix {
// Listen on the unix socket.
l, err := net.Listen("unix", s.options.HTTPListenAddress)
if err != nil {
return fmt.Errorf("Listen: %v", err)
}
// Start the http server.
err = http.Serve(l, nil)
if err != nil {
return fmt.Errorf("Serve: %v", err)
}
} else if s.options.HTTPSocketType == HTTPSocketTypeTCP {
// Start the http server.
err := http.ListenAndServe(s.options.HTTPListenAddress, nil)
if err != nil {
return fmt.Errorf("ListenAndServe: %v", err)
}
} else {
return fmt.Errorf("invalid socket options type: %v", s.options.HTTPSocketType)
}
} else {
// HINT: This is only a placeholder until the internal glue TCP server is implemented.
w := make(chan struct{})
<-w
}
return nil
}
// ServeHTTP implements the HTTP Handler interface of the http package.
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.bs.ServeHTTP(w, r)
}
//########################//
//### Server - Private ###//
//########################//
func (s *Server) handleOnNewSocketConnection(bs backend.BackendSocket) {
// Close the socket if incomming connections should be blocked.
if s.IsBlocked() {
bs.Close()
return
}
// Create a new socket value.
// The goroutines are started automatically.
newSocket(s, bs)
}