|
| 1 | +package servers |
| 2 | + |
| 3 | +import ( |
| 4 | + "log" |
| 5 | + "net" |
| 6 | + "net/http" |
| 7 | + "sync" |
| 8 | + |
| 9 | + "github.com/gorilla/mux" |
| 10 | + "github.com/gorilla/websocket" |
| 11 | + |
| 12 | + appServer "github.com/codemodify/systemkit-appserver" |
| 13 | + httpServer "github.com/codemodify/systemkit-appserver-http" |
| 14 | + channels "github.com/codemodify/systemkit-helpers-channels" |
| 15 | +) |
| 16 | + |
| 17 | +// WebScoketsRequestHandler - |
| 18 | +type WebScoketsRequestHandler func(inChannel chan []byte, outChannel chan []byte) |
| 19 | + |
| 20 | +// WebSocketsHandler - |
| 21 | +type WebSocketsHandler struct { |
| 22 | + Route string |
| 23 | + Handler WebScoketsRequestHandler |
| 24 | +} |
| 25 | + |
| 26 | +// WebScoketsServer - |
| 27 | +type WebScoketsServer struct { |
| 28 | + handlers []WebSocketsHandler |
| 29 | + routeToHandler map[string]WebSocketsHandler |
| 30 | + HTTPServer appServer.IServer |
| 31 | + peers []*websocket.Conn |
| 32 | + peersSync sync.RWMutex |
| 33 | + enableCORS bool |
| 34 | +} |
| 35 | + |
| 36 | +// NewWebSocketsServer - |
| 37 | +func NewWebSocketsServer(handlers []WebSocketsHandler) appServer.IServer { |
| 38 | + |
| 39 | + var thisRef = &WebScoketsServer{ |
| 40 | + handlers: handlers, |
| 41 | + routeToHandler: map[string]WebSocketsHandler{}, |
| 42 | + HTTPServer: nil, |
| 43 | + peers: []*websocket.Conn{}, |
| 44 | + peersSync: sync.RWMutex{}, |
| 45 | + } |
| 46 | + |
| 47 | + var lowLevelRequestHelper = func(rw http.ResponseWriter, r *http.Request) { |
| 48 | + r.Header["Origin"] = nil |
| 49 | + |
| 50 | + var handler WebSocketsHandler = thisRef.routeToHandler[r.URL.Path] |
| 51 | + |
| 52 | + var upgrader = websocket.Upgrader{ |
| 53 | + CheckOrigin: func(r *http.Request) bool { return thisRef.enableCORS }, |
| 54 | + } |
| 55 | + ws, err := upgrader.Upgrade(rw, r, nil) |
| 56 | + if err != nil { |
| 57 | + log.Print("upgrade: ", err) |
| 58 | + return |
| 59 | + } |
| 60 | + |
| 61 | + thisRef.setupCommunication(ws, &handler) |
| 62 | + } |
| 63 | + |
| 64 | + var HTTPHandlers = []httpServer.HTTPHandler{} |
| 65 | + |
| 66 | + for _, handler := range thisRef.handlers { |
| 67 | + thisRef.routeToHandler[handler.Route] = handler |
| 68 | + |
| 69 | + HTTPHandlers = append(HTTPHandlers, httpServer.HTTPHandler{ |
| 70 | + Route: handler.Route, |
| 71 | + Handler: lowLevelRequestHelper, |
| 72 | + Verb: "GET", |
| 73 | + }) |
| 74 | + } |
| 75 | + |
| 76 | + thisRef.HTTPServer = httpServer.NewHTTPServer(HTTPHandlers) |
| 77 | + |
| 78 | + return thisRef |
| 79 | +} |
| 80 | + |
| 81 | +// Run - Implement `IServer` |
| 82 | +func (thisRef *WebScoketsServer) Run(ipPort string, enableCORS bool) error { |
| 83 | + thisRef.enableCORS = enableCORS |
| 84 | + return thisRef.HTTPServer.Run(ipPort, enableCORS) |
| 85 | +} |
| 86 | + |
| 87 | +// PrepareRoutes - Implement `IServer` |
| 88 | +func (thisRef *WebScoketsServer) PrepareRoutes(router *mux.Router) { |
| 89 | + thisRef.HTTPServer.PrepareRoutes(router) |
| 90 | +} |
| 91 | + |
| 92 | +// RunOnExistingListenerAndRouter - Implement `IServer` |
| 93 | +func (thisRef *WebScoketsServer) RunOnExistingListenerAndRouter(listener net.Listener, router *mux.Router, enableCORS bool) { |
| 94 | + thisRef.HTTPServer.RunOnExistingListenerAndRouter(listener, router, enableCORS) |
| 95 | +} |
| 96 | + |
| 97 | +func (thisRef *WebScoketsServer) setupCommunication(ws *websocket.Conn, handler *WebSocketsHandler) { |
| 98 | + // DEBUG: fmt.Println("AppServer-WebScokets-DEBUG: setupCommunication - START") |
| 99 | + |
| 100 | + thisRef.addPeer(ws) |
| 101 | + |
| 102 | + var inChannel = make(chan []byte) // data from WS |
| 103 | + var outChannel = make(chan []byte) // data to WS |
| 104 | + |
| 105 | + go handler.Handler(inChannel, outChannel) |
| 106 | + |
| 107 | + var once sync.Once |
| 108 | + closeInChannel := func() { |
| 109 | + close(inChannel) |
| 110 | + } |
| 111 | + |
| 112 | + var wg sync.WaitGroup |
| 113 | + |
| 114 | + wg.Add(1) |
| 115 | + go func() { |
| 116 | + // DEBUG: fmt.Println("AppServer-WebScokets-DEBUG: SEND-TO-PEER - START") |
| 117 | + |
| 118 | + for { |
| 119 | + data, readOk := <-outChannel |
| 120 | + if !readOk { // if CHANNEL closed - means communication ended by the handler |
| 121 | + // DEBUG: fmt.Println(fmt.Sprint("AppServer-WebScokets-DEBUG: SEND-TO-PEER - communication ended by the handler")) |
| 122 | + break |
| 123 | + } |
| 124 | + |
| 125 | + // DEBUG: fmt.Println(fmt.Sprint("AppServer-WebScokets-DEBUG: SEND-TO-PEER - DATA: ", string(data))) |
| 126 | + |
| 127 | + err := ws.WriteMessage(websocket.TextMessage, data) |
| 128 | + if err != nil { // if can't send - means communication ended by the peer |
| 129 | + // DEBUG: fmt.Println(fmt.Sprint("AppServer-WebScokets-DEBUG: SEND-TO-PEER - send - communication ended by the peer")) |
| 130 | + break |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + once.Do(closeInChannel) |
| 135 | + |
| 136 | + // DEBUG: fmt.Println("AppServer-WebScokets-DEBUG: SEND-TO-PEER - END") |
| 137 | + wg.Done() |
| 138 | + |
| 139 | + }() |
| 140 | + |
| 141 | + wg.Add(1) |
| 142 | + go func() { |
| 143 | + // DEBUG: fmt.Println("AppServer-WebScokets-DEBUG: READ-FROM-PEER - START") |
| 144 | + |
| 145 | + for { |
| 146 | + _, data, err := ws.ReadMessage() |
| 147 | + if err != nil { // if can't read - means communication ended by the peer |
| 148 | + // DEBUG: fmt.Println(fmt.Sprint("AppServer-WebScokets-DEBUG: SEND-FROM-PEER - read - communication ended by the peer")) |
| 149 | + once.Do(closeInChannel) |
| 150 | + break |
| 151 | + } |
| 152 | + |
| 153 | + // DEBUG: fmt.Println(fmt.Sprint("AppServer-WebScokets-DEBUG: READ-FROM-PEER - DATA: ", string(data))) |
| 154 | + |
| 155 | + if channels.IsClosed(inChannel) { |
| 156 | + break |
| 157 | + } |
| 158 | + inChannel <- []byte(data) |
| 159 | + } |
| 160 | + |
| 161 | + // DEBUG: fmt.Println("AppServer-WebScokets-DEBUG: READ-FROM-PEER - END") |
| 162 | + wg.Done() |
| 163 | + }() |
| 164 | + |
| 165 | + wg.Wait() |
| 166 | + thisRef.removePeer(ws) |
| 167 | + |
| 168 | + // DEBUG: fmt.Println("AppServer-WebScokets-DEBUG: setupCommunication - DONE") |
| 169 | +} |
| 170 | + |
| 171 | +// SendToAllPeers - |
| 172 | +func (thisRef *WebScoketsServer) SendToAllPeers(data []byte) { |
| 173 | + thisRef.peersSync.RLock() |
| 174 | + defer thisRef.peersSync.RUnlock() |
| 175 | + |
| 176 | + for _, conn := range thisRef.peers { |
| 177 | + conn.WriteMessage(websocket.TextMessage, data) |
| 178 | + } |
| 179 | +} |
| 180 | + |
| 181 | +func (thisRef *WebScoketsServer) addPeer(peer *websocket.Conn) { |
| 182 | + thisRef.peersSync.Lock() |
| 183 | + defer thisRef.peersSync.Unlock() |
| 184 | + |
| 185 | + // DEBUG: fmt.Println("AppServer-WebScokets-DEBUG: addPeer") |
| 186 | + |
| 187 | + thisRef.peers = append(thisRef.peers, peer) |
| 188 | +} |
| 189 | + |
| 190 | +func (thisRef *WebScoketsServer) removePeer(peer *websocket.Conn) { |
| 191 | + thisRef.peersSync.Lock() |
| 192 | + defer thisRef.peersSync.Unlock() |
| 193 | + |
| 194 | + // DEBUG: fmt.Println("AppServer-WebScokets-DEBUG: removePeer") |
| 195 | + |
| 196 | + index := -1 |
| 197 | + for i, conn := range thisRef.peers { |
| 198 | + if conn == peer { |
| 199 | + index = i |
| 200 | + break |
| 201 | + } |
| 202 | + } |
| 203 | + if index != -1 { |
| 204 | + thisRef.peers = append(thisRef.peers[:index], thisRef.peers[index+1:]...) |
| 205 | + } |
| 206 | + |
| 207 | + peer.Close() |
| 208 | +} |
0 commit comments