forked from kataras/iris
-
Notifications
You must be signed in to change notification settings - Fork 0
/
websocket.go
1215 lines (1061 loc) · 41.7 KB
/
websocket.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package iris
import (
"bytes"
"encoding/json"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/iris-contrib/logger"
"github.com/iris-contrib/websocket"
"github.com/kataras/iris/config"
"github.com/kataras/iris/utils"
)
// ---------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------
// --------------------------------Websocket implementation-------------------------------------------------
// Global functions in order to be able to use unlimitted number of websocket servers on each iris station--
// ---------------------------------------------------------------------------------------------------------
// NewWebsocketServer creates a websocket server and returns it
func NewWebsocketServer(c *config.Websocket) WebsocketServer {
return newWebsocketServer(c)
}
// RegisterWebsocketServer registers the handlers for the websocket server
// it's a bridge between station and websocket server
func RegisterWebsocketServer(station FrameworkAPI, server WebsocketServer, logger *logger.Logger) {
c := server.Config()
if c.Endpoint == "" {
return
}
websocketHandler := func(ctx *Context) {
if err := server.Upgrade(ctx); err != nil {
logger.Panic(err)
}
}
if c.Headers != nil && len(c.Headers) > 0 { // only for performance matter just re-create the websocketHandler if we have headers to set
websocketHandler = func(ctx *Context) {
for k, v := range c.Headers {
ctx.SetHeader(k, v)
}
if err := server.Upgrade(ctx); err != nil {
logger.Panic(err)
}
}
}
station.Get(c.Endpoint, websocketHandler)
// serve the client side on domain:port/iris-ws.js
station.StaticContent("/iris-ws.js", "application/json", websocketClientSource)
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// --------------------------------WebsocketServer implementation-----------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
type (
// WebsocketConnectionFunc is the callback which fires when a client/websocketConnection is connected to the websocketServer.
// Receives one parameter which is the WebsocketConnection
WebsocketConnectionFunc func(WebsocketConnection)
// WebsocketRooms is just a map with key a string and value slice of string
WebsocketRooms map[string][]string
// websocketRoomPayload is used as payload from the websocketConnection to the websocketServer
websocketRoomPayload struct {
roomName string
websocketConnectionID string
}
// payloads, websocketConnection -> websocketServer
websocketMessagePayload struct {
from string
to string
data []byte
}
// WebsocketServer is the websocket server, listens on the config's port, the critical part is the event OnConnection
WebsocketServer interface {
Config() *config.Websocket
Upgrade(ctx *Context) error
OnConnection(cb WebsocketConnectionFunc)
}
websocketServer struct {
config *config.Websocket
upgrader websocket.Upgrader
put chan *websocketConnection
free chan *websocketConnection
websocketConnections map[string]*websocketConnection
join chan websocketRoomPayload
leave chan websocketRoomPayload
rooms WebsocketRooms // by default a websocketConnection is joined to a room which has the websocketConnection id as its name
mu sync.Mutex // for rooms
messages chan websocketMessagePayload
onConnectionListeners []WebsocketConnectionFunc
//websocketConnectionPool *sync.Pool // sadly I can't make this because the websocket websocketConnection is live until is closed.
}
)
var _ WebsocketServer = &websocketServer{}
// websocketServer implementation
// newWebsocketServer creates a websocket websocketServer and returns it
func newWebsocketServer(c *config.Websocket) *websocketServer {
s := &websocketServer{
config: c,
put: make(chan *websocketConnection),
free: make(chan *websocketConnection),
websocketConnections: make(map[string]*websocketConnection),
join: make(chan websocketRoomPayload, 1), // buffered because join can be called immediately on websocketConnection connected
leave: make(chan websocketRoomPayload),
rooms: make(WebsocketRooms),
messages: make(chan websocketMessagePayload, 1), // buffered because messages can be sent/received immediately on websocketConnection connected
onConnectionListeners: make([]WebsocketConnectionFunc, 0),
}
s.upgrader = websocket.Custom(s.handleWebsocketConnection, s.config.ReadBufferSize, s.config.WriteBufferSize, false)
go s.serve() // start the websocketServer automatically
return s
}
func (s *websocketServer) Config() *config.Websocket {
return s.config
}
func (s *websocketServer) Upgrade(ctx *Context) error {
return s.upgrader.Upgrade(ctx)
}
func (s *websocketServer) handleWebsocketConnection(websocketConn *websocket.Conn) {
c := newWebsocketConnection(websocketConn, s)
s.put <- c
go c.writer()
c.reader()
}
func (s *websocketServer) OnConnection(cb WebsocketConnectionFunc) {
s.onConnectionListeners = append(s.onConnectionListeners, cb)
}
func (s *websocketServer) joinRoom(roomName string, connID string) {
s.mu.Lock()
if s.rooms[roomName] == nil {
s.rooms[roomName] = make([]string, 0)
}
s.rooms[roomName] = append(s.rooms[roomName], connID)
s.mu.Unlock()
}
func (s *websocketServer) leaveRoom(roomName string, connID string) {
s.mu.Lock()
if s.rooms[roomName] != nil {
for i := range s.rooms[roomName] {
if s.rooms[roomName][i] == connID {
s.rooms[roomName][i] = s.rooms[roomName][len(s.rooms[roomName])-1]
s.rooms[roomName] = s.rooms[roomName][:len(s.rooms[roomName])-1]
break
}
}
if len(s.rooms[roomName]) == 0 { // if room is empty then delete it
delete(s.rooms, roomName)
}
}
s.mu.Unlock()
}
func (s *websocketServer) serve() {
for {
select {
case c := <-s.put: // websocketConnection connected
s.websocketConnections[c.id] = c
// make and join a room with the websocketConnection's id
s.rooms[c.id] = make([]string, 0)
s.rooms[c.id] = []string{c.id}
for i := range s.onConnectionListeners {
s.onConnectionListeners[i](c)
}
case c := <-s.free: // websocketConnection closed
if _, found := s.websocketConnections[c.id]; found {
// leave from all rooms
for roomName := range s.rooms {
s.leaveRoom(roomName, c.id)
}
delete(s.websocketConnections, c.id)
close(c.send)
c.fireDisconnect()
}
case join := <-s.join:
s.joinRoom(join.roomName, join.websocketConnectionID)
case leave := <-s.leave:
if _, found := s.websocketConnections[leave.websocketConnectionID]; found {
s.leaveRoom(leave.roomName, leave.websocketConnectionID)
}
case msg := <-s.messages: // message received from the websocketConnection
if msg.to != All && msg.to != NotMe && s.rooms[msg.to] != nil {
// it suppose to send the message to a room
for _, websocketConnectionIDInsideRoom := range s.rooms[msg.to] {
if c, connected := s.websocketConnections[websocketConnectionIDInsideRoom]; connected {
c.send <- msg.data //here we send it without need to continue below
} else {
// the websocketConnection is not connected but it's inside the room, we remove it on disconnect but for ANY CASE:
s.leaveRoom(c.id, msg.to)
}
}
} else { // it suppose to send the message to all opened websocketConnections or to all except the sender
for connID, c := range s.websocketConnections {
if msg.to != All { // if it's not suppose to send to all websocketConnections (including itself)
if msg.to == NotMe && msg.from == connID { // if broadcast to other websocketConnections except this
continue //here we do the opossite of previous block, just skip this websocketConnection when it's suppose to send the message to all websocketConnections except the sender
}
}
select {
case s.websocketConnections[connID].send <- msg.data: //send the message back to the websocketConnection in order to send it to the client
default:
close(c.send)
delete(s.websocketConnections, connID)
c.fireDisconnect()
}
}
}
}
}
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// --------------------------------WebsocketEmmiter implementation----------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
const (
// All is the string which the WebsocketEmmiter use to send a message to all
All = ""
// NotMe is the string which the WebsocketEmmiter use to send a message to all except this websocketConnection
NotMe = ";iris;to;all;except;me;"
// Broadcast is the string which the WebsocketEmmiter use to send a message to all except this websocketConnection, same as 'NotMe'
Broadcast = NotMe
)
type (
// WebsocketEmmiter is the message/or/event manager
WebsocketEmmiter interface {
// EmitMessage sends a native websocket message
EmitMessage([]byte) error
// Emit sends a message on a particular event
Emit(string, interface{}) error
}
websocketEmmiter struct {
conn *websocketConnection
to string
}
)
var _ WebsocketEmmiter = &websocketEmmiter{}
func newWebsocketEmmiter(c *websocketConnection, to string) *websocketEmmiter {
return &websocketEmmiter{conn: c, to: to}
}
func (e *websocketEmmiter) EmitMessage(nativeMessage []byte) error {
mp := websocketMessagePayload{e.conn.id, e.to, nativeMessage}
e.conn.websocketServer.messages <- mp
return nil
}
func (e *websocketEmmiter) Emit(event string, data interface{}) error {
message, err := websocketMessageSerialize(event, data)
if err != nil {
return err
}
e.EmitMessage([]byte(message))
return nil
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// --------------------------------WebsocketWebsocketConnection implementation-------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
type (
// WebsocketDisconnectFunc is the callback which fires when a client/websocketConnection closed
WebsocketDisconnectFunc func()
// WebsocketErrorFunc is the callback which fires when an error happens
WebsocketErrorFunc (func(string))
// WebsocketNativeMessageFunc is the callback for native websocket messages, receives one []byte parameter which is the raw client's message
WebsocketNativeMessageFunc func([]byte)
// WebsocketMessageFunc is the second argument to the WebsocketEmmiter's Emit functions.
// A callback which should receives one parameter of type string, int, bool or any valid JSON/Go struct
WebsocketMessageFunc interface{}
// WebsocketConnection is the client
WebsocketConnection interface {
// WebsocketEmmiter implements EmitMessage & Emit
WebsocketEmmiter
// ID returns the websocketConnection's identifier
ID() string
// OnDisconnect registers a callback which fires when this websocketConnection is closed by an error or manual
OnDisconnect(WebsocketDisconnectFunc)
// OnError registers a callback which fires when this websocketConnection occurs an error
OnError(WebsocketErrorFunc)
// EmitError can be used to send a custom error message to the websocketConnection
//
// It does nothing more than firing the OnError listeners. It doesn't sends anything to the client.
EmitError(errorMessage string)
// To defines where websocketServer should send a message
// returns an emmiter to send messages
To(string) WebsocketEmmiter
// OnMessage registers a callback which fires when native websocket message received
OnMessage(WebsocketNativeMessageFunc)
// On registers a callback to a particular event which fires when a message to this event received
On(string, WebsocketMessageFunc)
// Join join a websocketConnection to a room, it doesn't check if websocketConnection is already there, so care
Join(string)
// Leave removes a websocketConnection from a room
Leave(string)
// Disconnect disconnects the client, close the underline websocket conn and removes it from the conn list
// returns the error, if any, from the underline connection
Disconnect() error
}
websocketConnection struct {
underline *websocket.Conn
id string
send chan []byte
onDisconnectListeners []WebsocketDisconnectFunc
onErrorListeners []WebsocketErrorFunc
onNativeMessageListeners []WebsocketNativeMessageFunc
onEventListeners map[string][]WebsocketMessageFunc
// these were maden for performance only
self WebsocketEmmiter // pre-defined emmiter than sends message to its self client
broadcast WebsocketEmmiter // pre-defined emmiter that sends message to all except this
all WebsocketEmmiter // pre-defined emmiter which sends message to all clients
websocketServer *websocketServer
}
)
var _ WebsocketConnection = &websocketConnection{}
func newWebsocketConnection(websocketConn *websocket.Conn, s *websocketServer) *websocketConnection {
c := &websocketConnection{
id: utils.RandomString(64),
underline: websocketConn,
send: make(chan []byte, 256),
onDisconnectListeners: make([]WebsocketDisconnectFunc, 0),
onErrorListeners: make([]WebsocketErrorFunc, 0),
onNativeMessageListeners: make([]WebsocketNativeMessageFunc, 0),
onEventListeners: make(map[string][]WebsocketMessageFunc, 0),
websocketServer: s,
}
c.self = newWebsocketEmmiter(c, c.id)
c.broadcast = newWebsocketEmmiter(c, NotMe)
c.all = newWebsocketEmmiter(c, All)
return c
}
func (c *websocketConnection) write(websocketMessageType int, data []byte) error {
c.underline.SetWriteDeadline(time.Now().Add(c.websocketServer.config.WriteTimeout))
return c.underline.WriteMessage(websocketMessageType, data)
}
func (c *websocketConnection) writer() {
ticker := time.NewTicker(c.websocketServer.config.PingPeriod)
defer func() {
ticker.Stop()
c.Disconnect()
}()
for {
select {
case msg, ok := <-c.send:
if !ok {
defer func() {
// FIX FOR: https://github.com/kataras/iris/issues/175
// AS I TESTED ON TRIDENT ENGINE (INTERNET EXPLORER/SAFARI):
// NAVIGATE TO SITE, CLOSE THE TAB, NOTHING HAPPENS
// CLOSE THE WHOLE BROWSER, THEN THE c.conn is NOT NILL BUT ALL ITS FUNCTIONS PANICS, MEANS THAT IS THE STRUCT IS NOT NIL BUT THE WRITER/READER ARE NIL
// THE ONLY SOLUTION IS TO RECOVER HERE AT ANY PANIC
// THE FRAMETYPE = 8, c.closeSend = true
// NOTE THAT THE CLIENT IS NOT DISCONNECTED UNTIL THE WHOLE WINDOW BROWSER CLOSED, this is engine's bug.
//
if err := recover(); err != nil {
ticker.Stop()
c.Disconnect()
}
}()
c.write(websocket.CloseMessage, []byte{})
return
}
c.underline.SetWriteDeadline(time.Now().Add(c.websocketServer.config.WriteTimeout))
res, err := c.underline.NextWriter(websocket.TextMessage)
if err != nil {
return
}
res.Write(msg)
n := len(c.send)
for i := 0; i < n; i++ {
res.Write(<-c.send)
}
if err := res.Close(); err != nil {
return
}
// if err := c.write(websocket.TextMessage, msg); err != nil {
// return
// }
case <-ticker.C:
if err := c.write(websocket.PingMessage, []byte{}); err != nil {
return
}
}
}
}
func (c *websocketConnection) reader() {
defer func() {
c.Disconnect()
}()
conn := c.underline
conn.SetReadLimit(c.websocketServer.config.MaxMessageSize)
conn.SetReadDeadline(time.Now().Add(c.websocketServer.config.PongTimeout))
conn.SetPongHandler(func(s string) error {
conn.SetReadDeadline(time.Now().Add(c.websocketServer.config.PongTimeout))
return nil
})
for {
if _, data, err := conn.ReadMessage(); err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
c.EmitError(err.Error())
}
break
} else {
c.messageReceived(data)
}
}
}
// messageReceived checks the incoming message and fire the nativeMessage listeners or the event listeners (iris-ws custom message)
func (c *websocketConnection) messageReceived(data []byte) {
if bytes.HasPrefix(data, websocketMessagePrefixBytes) {
customData := string(data)
//it's a custom iris-ws message
receivedEvt := getWebsocketCustomEvent(customData)
listeners := c.onEventListeners[receivedEvt]
if listeners == nil { // if not listeners for this event exit from here
return
}
customMessage, err := websocketMessageDeserialize(receivedEvt, customData)
if customMessage == nil || err != nil {
return
}
for i := range listeners {
if fn, ok := listeners[i].(func()); ok { // its a simple func(){} callback
fn()
} else if fnString, ok := listeners[i].(func(string)); ok {
if msgString, is := customMessage.(string); is {
fnString(msgString)
} else if msgInt, is := customMessage.(int); is {
// here if websocketServer side waiting for string but client side sent an int, just convert this int to a string
fnString(strconv.Itoa(msgInt))
}
} else if fnInt, ok := listeners[i].(func(int)); ok {
fnInt(customMessage.(int))
} else if fnBool, ok := listeners[i].(func(bool)); ok {
fnBool(customMessage.(bool))
} else if fnBytes, ok := listeners[i].(func([]byte)); ok {
fnBytes(customMessage.([]byte))
} else {
listeners[i].(func(interface{}))(customMessage)
}
}
} else {
// it's native websocket message
for i := range c.onNativeMessageListeners {
c.onNativeMessageListeners[i](data)
}
}
}
func (c *websocketConnection) ID() string {
return c.id
}
func (c *websocketConnection) fireDisconnect() {
for i := range c.onDisconnectListeners {
c.onDisconnectListeners[i]()
}
}
func (c *websocketConnection) OnDisconnect(cb WebsocketDisconnectFunc) {
c.onDisconnectListeners = append(c.onDisconnectListeners, cb)
}
func (c *websocketConnection) OnError(cb WebsocketErrorFunc) {
c.onErrorListeners = append(c.onErrorListeners, cb)
}
func (c *websocketConnection) EmitError(errorMessage string) {
for _, cb := range c.onErrorListeners {
cb(errorMessage)
}
}
func (c *websocketConnection) To(to string) WebsocketEmmiter {
if to == NotMe { // if send to all except me, then return the pre-defined emmiter, and so on
return c.broadcast
} else if to == All {
return c.all
} else if to == c.id {
return c.self
}
// is an emmiter to another client/websocketConnection
return newWebsocketEmmiter(c, to)
}
func (c *websocketConnection) EmitMessage(nativeMessage []byte) error {
return c.self.EmitMessage(nativeMessage)
}
func (c *websocketConnection) Emit(event string, message interface{}) error {
return c.self.Emit(event, message)
}
func (c *websocketConnection) OnMessage(cb WebsocketNativeMessageFunc) {
c.onNativeMessageListeners = append(c.onNativeMessageListeners, cb)
}
func (c *websocketConnection) On(event string, cb WebsocketMessageFunc) {
if c.onEventListeners[event] == nil {
c.onEventListeners[event] = make([]WebsocketMessageFunc, 0)
}
c.onEventListeners[event] = append(c.onEventListeners[event], cb)
}
func (c *websocketConnection) Join(roomName string) {
payload := websocketRoomPayload{roomName, c.id}
c.websocketServer.join <- payload
}
func (c *websocketConnection) Leave(roomName string) {
payload := websocketRoomPayload{roomName, c.id}
c.websocketServer.leave <- payload
}
func (c *websocketConnection) Disconnect() error {
c.websocketServer.free <- c // leaves from all rooms, fires the disconnect listeners and finally remove from conn list
return c.underline.Close()
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// -----------------websocket messages and de/serialization implementation--------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
/*
serializer, [de]websocketMessageSerialize the messages from the client to the websocketServer and from the websocketServer to the client
*/
// The same values are exists on client side also
const (
websocketStringMessageType websocketMessageType = iota
websocketIntMessageType
websocketBoolMessageType
websocketBytesMessageType
websocketJSONMessageType
)
const (
websocketMessagePrefix = "iris-websocket-message:"
websocketMessageSeparator = ";"
websocketMessagePrefixLen = len(websocketMessagePrefix)
websocketMessageSeparatorLen = len(websocketMessageSeparator)
websocketMessagePrefixAndSepIdx = websocketMessagePrefixLen + websocketMessageSeparatorLen - 1
websocketMessagePrefixIdx = websocketMessagePrefixLen - 1
websocketMessageSeparatorIdx = websocketMessageSeparatorLen - 1
)
var (
websocketMessageSeparatorByte = websocketMessageSeparator[0]
websocketMessageBuffer = utils.NewBufferPool(256)
websocketMessagePrefixBytes = []byte(websocketMessagePrefix)
)
type (
websocketMessageType uint8
)
func (m websocketMessageType) String() string {
return strconv.Itoa(int(m))
}
func (m websocketMessageType) Name() string {
if m == websocketStringMessageType {
return "string"
} else if m == websocketIntMessageType {
return "int"
} else if m == websocketBoolMessageType {
return "bool"
} else if m == websocketBytesMessageType {
return "[]byte"
} else if m == websocketJSONMessageType {
return "json"
}
return "Invalid(" + m.String() + ")"
}
// websocketMessageSerialize serializes a custom websocket message from websocketServer to be delivered to the client
// returns the string form of the message
// Supported data types are: string, int, bool, bytes and JSON.
func websocketMessageSerialize(event string, data interface{}) (string, error) {
var msgType websocketMessageType
var dataMessage string
if s, ok := data.(string); ok {
msgType = websocketStringMessageType
dataMessage = s
} else if i, ok := data.(int); ok {
msgType = websocketIntMessageType
dataMessage = strconv.Itoa(i)
} else if b, ok := data.(bool); ok {
msgType = websocketBoolMessageType
dataMessage = strconv.FormatBool(b)
} else if by, ok := data.([]byte); ok {
msgType = websocketBytesMessageType
dataMessage = string(by)
} else {
//we suppose is json
res, err := json.Marshal(data)
if err != nil {
return "", err
}
msgType = websocketJSONMessageType
dataMessage = string(res)
}
b := websocketMessageBuffer.Get()
b.WriteString(websocketMessagePrefix)
b.WriteString(event)
b.WriteString(websocketMessageSeparator)
b.WriteString(msgType.String())
b.WriteString(websocketMessageSeparator)
b.WriteString(dataMessage)
dataMessage = b.String()
websocketMessageBuffer.Put(b)
return dataMessage, nil
}
// websocketMessageDeserialize deserializes a custom websocket message from the client
// ex: iris-websocket-message;chat;4;themarshaledstringfromajsonstruct will return 'hello' as string
// Supported data types are: string, int, bool, bytes and JSON.
func websocketMessageDeserialize(event string, websocketMessage string) (message interface{}, err error) {
t, formaterr := strconv.Atoi(websocketMessage[websocketMessagePrefixAndSepIdx+len(event)+1 : websocketMessagePrefixAndSepIdx+len(event)+2]) // in order to iris-websocket-message;user;-> 4
if formaterr != nil {
return nil, formaterr
}
_type := websocketMessageType(t)
_message := websocketMessage[websocketMessagePrefixAndSepIdx+len(event)+3:] // in order to iris-websocket-message;user;4; -> themarshaledstringfromajsonstruct
if _type == websocketStringMessageType {
message = string(_message)
} else if _type == websocketIntMessageType {
message, err = strconv.Atoi(_message)
} else if _type == websocketBoolMessageType {
message, err = strconv.ParseBool(_message)
} else if _type == websocketBytesMessageType {
message = []byte(_message)
} else if _type == websocketJSONMessageType {
err = json.Unmarshal([]byte(_message), message)
} else {
return nil, fmt.Errorf("Type %s is invalid for message: %s", _type.Name(), websocketMessage)
}
return
}
// getWebsocketCustomEvent return empty string when the websocketMessage is native message
func getWebsocketCustomEvent(websocketMessage string) string {
if len(websocketMessage) < websocketMessagePrefixAndSepIdx {
return ""
}
s := websocketMessage[websocketMessagePrefixAndSepIdx:]
evt := s[:strings.IndexByte(s, websocketMessageSeparatorByte)]
return evt
}
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// ----------------Client side websocket javascript source code ------------------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
var websocketClientSource = []byte(`var websocketStringMessageType = 0;
var websocketIntMessageType = 1;
var websocketBoolMessageType = 2;
// bytes is missing here for reasons I will explain somewhen
var websocketJSONMessageType = 4;
var websocketMessagePrefix = "iris-websocket-message:";
var websocketMessageSeparator = ";";
var websocketMessagePrefixLen = websocketMessagePrefix.length;
var websocketMessageSeparatorLen = websocketMessageSeparator.length;
var websocketMessagePrefixAndSepIdx = websocketMessagePrefixLen + websocketMessageSeparatorLen - 1;
var websocketMessagePrefixIdx = websocketMessagePrefixLen - 1;
var websocketMessageSeparatorIdx = websocketMessageSeparatorLen - 1;
var Ws = (function () {
//
function Ws(endpoint, protocols) {
var _this = this;
// events listeners
this.connectListeners = [];
this.disconnectListeners = [];
this.nativeMessageListeners = [];
this.messageListeners = {};
if (!window["WebSocket"]) {
return;
}
if (endpoint.indexOf("ws") == -1) {
endpoint = "ws://" + endpoint;
}
if (protocols != null && protocols.length > 0) {
this.conn = new WebSocket(endpoint, protocols);
}
else {
this.conn = new WebSocket(endpoint);
}
this.conn.onopen = (function (evt) {
_this.fireConnect();
_this.isReady = true;
return null;
});
this.conn.onclose = (function (evt) {
_this.fireDisconnect();
return null;
});
this.conn.onmessage = (function (evt) {
_this.messageReceivedFromConn(evt);
});
}
//utils
Ws.prototype.isNumber = function (obj) {
return !isNaN(obj - 0) && obj !== null && obj !== "" && obj !== false;
};
Ws.prototype.isString = function (obj) {
return Object.prototype.toString.call(obj) == "[object String]";
};
Ws.prototype.isBoolean = function (obj) {
return typeof obj === 'boolean' ||
(typeof obj === 'object' && typeof obj.valueOf() === 'boolean');
};
Ws.prototype.isJSON = function (obj) {
try {
JSON.parse(obj);
}
catch (e) {
return false;
}
return true;
};
//
// messages
Ws.prototype._msg = function (event, websocketMessageType, dataMessage) {
return websocketMessagePrefix + event + websocketMessageSeparator + String(websocketMessageType) + websocketMessageSeparator + dataMessage;
};
Ws.prototype.encodeMessage = function (event, data) {
var m = "";
var t = 0;
if (this.isNumber(data)) {
t = websocketIntMessageType;
m = data.toString();
}
else if (this.isBoolean(data)) {
t = websocketBoolMessageType;
m = data.toString();
}
else if (this.isString(data)) {
t = websocketStringMessageType;
m = data.toString();
}
else if (this.isJSON(data)) {
//propably json-object
t = websocketJSONMessageType;
m = JSON.stringify(data);
}
else {
console.log("Invalid");
}
return this._msg(event, t, m);
};
Ws.prototype.decodeMessage = function (event, websocketMessage) {
//iris-websocket-message;user;4;themarshaledstringfromajsonstruct
var skipLen = websocketMessagePrefixLen + websocketMessageSeparatorLen + event.length + 2;
if (websocketMessage.length < skipLen + 1) {
return null;
}
var websocketMessageType = parseInt(websocketMessage.charAt(skipLen - 2));
var theMessage = websocketMessage.substring(skipLen, websocketMessage.length);
if (websocketMessageType == websocketIntMessageType) {
return parseInt(theMessage);
}
else if (websocketMessageType == websocketBoolMessageType) {
return Boolean(theMessage);
}
else if (websocketMessageType == websocketStringMessageType) {
return theMessage;
}
else if (websocketMessageType == websocketJSONMessageType) {
return JSON.parse(theMessage);
}
else {
return null; // invalid
}
};
Ws.prototype.getWebsocketCustomEvent = function (websocketMessage) {
if (websocketMessage.length < websocketMessagePrefixAndSepIdx) {
return "";
}
var s = websocketMessage.substring(websocketMessagePrefixAndSepIdx, websocketMessage.length);
var evt = s.substring(0, s.indexOf(websocketMessageSeparator));
return evt;
};
Ws.prototype.getCustomMessage = function (event, websocketMessage) {
var eventIdx = websocketMessage.indexOf(event + websocketMessageSeparator);
var s = websocketMessage.substring(eventIdx + event.length + websocketMessageSeparator.length + 2, websocketMessage.length);
return s;
};
//
// Ws Events
// messageReceivedFromConn this is the func which decides
// if it's a native websocket message or a custom iris-ws message
// if native message then calls the fireNativeMessage
// else calls the fireMessage
//
// remember Iris gives you the freedom of native websocket messages if you don't want to use this client side at all.
Ws.prototype.messageReceivedFromConn = function (evt) {
//check if iris-ws message
var message = evt.data;
if (message.indexOf(websocketMessagePrefix) != -1) {
var event_1 = this.getWebsocketCustomEvent(message);
if (event_1 != "") {
// it's a custom message
this.fireMessage(event_1, this.getCustomMessage(event_1, message));
return;
}
}
// it's a native websocket message
this.fireNativeMessage(message);
};
Ws.prototype.OnConnect = function (fn) {
if (this.isReady) {
fn();
}
this.connectListeners.push(fn);
};
Ws.prototype.fireConnect = function () {
for (var i = 0; i < this.connectListeners.length; i++) {
this.connectListeners[i]();
}
};
Ws.prototype.OnDisconnect = function (fn) {
this.disconnectListeners.push(fn);
};
Ws.prototype.fireDisconnect = function () {
for (var i = 0; i < this.disconnectListeners.length; i++) {
this.disconnectListeners[i]();
}
};
Ws.prototype.OnMessage = function (cb) {
this.nativeMessageListeners.push(cb);
};
Ws.prototype.fireNativeMessage = function (websocketMessage) {
for (var i = 0; i < this.nativeMessageListeners.length; i++) {
this.nativeMessageListeners[i](websocketMessage);
}
};
Ws.prototype.On = function (event, cb) {
if (this.messageListeners[event] == null || this.messageListeners[event] == undefined) {
this.messageListeners[event] = [];
}
this.messageListeners[event].push(cb);
};
Ws.prototype.fireMessage = function (event, message) {
for (var key in this.messageListeners) {
if (this.messageListeners.hasOwnProperty(key)) {
if (key == event) {
for (var i = 0; i < this.messageListeners[key].length; i++) {
this.messageListeners[key][i](message);
}
}
}
}
};
//
// Ws Actions
Ws.prototype.Disconnect = function () {
this.conn.close();
};
// EmitMessage sends a native websocket message
Ws.prototype.EmitMessage = function (websocketMessage) {
this.conn.send(websocketMessage);
};
// Emit sends an iris-custom websocket message
Ws.prototype.Emit = function (event, data) {
var messageStr = this.encodeMessage(event, data);
this.EmitMessage(messageStr);
};
return Ws;
}());
`)
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
// ----------------Client side websocket commented typescript source code --------------
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
/*
const websocketStringMessageType = 0;
const websocketIntMessageType = 1;
const websocketBoolMessageType = 2;
// bytes is missing here for reasons I will explain somewhen
const websocketJSONMessageType = 4;
const websocketMessagePrefix = "iris-websocket-message:";
const websocketMessageSeparator = ";";
const websocketMessagePrefixLen = websocketMessagePrefix.length;
var websocketMessageSeparatorLen = websocketMessageSeparator.length;
var websocketMessagePrefixAndSepIdx = websocketMessagePrefixLen + websocketMessageSeparatorLen - 1;
var websocketMessagePrefixIdx = websocketMessagePrefixLen - 1;
var websocketMessageSeparatorIdx = websocketMessageSeparatorLen - 1;
type onConnectFunc = () => void;
type onWebsocketDisconnectFunc = () => void;
type onWebsocketNativeMessageFunc = (websocketMessage: string) => void;
type onMessageFunc = (message: any) => void;
class Ws {
private conn: WebSocket;
private isReady: boolean;
// events listeners
private connectListeners: onConnectFunc[] = [];
private disconnectListeners: onWebsocketDisconnectFunc[] = [];
private nativeMessageListeners: onWebsocketNativeMessageFunc[] = [];
private messageListeners: { [event: string]: onMessageFunc[] } = {};
//
constructor(endpoint: string, protocols?: string[]) {
if (!window["WebSocket"]) {
return;
}
if (endpoint.indexOf("ws") == -1) {
endpoint = "ws://" + endpoint;
}
if (protocols != null && protocols.length > 0) {
this.conn = new WebSocket(endpoint, protocols);
} else {