func (handler *handler) proxyConnectionTo(server *websocket.Conn) { handler.logger.Debugf("Output Proxy: Starting to listen to server %v", server.RemoteAddr().String()) var logMessage []byte defer server.Close() count := 0 for { _, data, err := server.ReadMessage() if err != nil { handler.logger.Errorf("Output Proxy: Error reading from the server - %v - %v", err, server.RemoteAddr().String()) handler.Done() return } handler.logger.Debugf("Output Proxy: Got message from server %v bytes", len(logMessage)) count++ err = handler.writeMessage(data) if err != nil { handler.logger.Errorf("Output Proxy: Error writing to client websocket - %v", err) return } } }
func newClient(ws *websocket.Conn, h *hub, srv *wsServer) *wsClient { if ws == nil { log.Panicln("ws cannot be nil") } if srv == nil { log.Panicln("server cannot be nil") } maxID++ return &wsClient{ id: maxID, ws: ws, h: h, srv: srv, subs: make(map[string]string), inMsgChan: make(chan *wsMessage), outMsgChan: make(chan *wsMessage), doneChan: make(chan bool), socketID: sha1Sum(fmt.Sprintf("%s-%s-%d", ws.RemoteAddr().String(), ws.LocalAddr().String(), maxID)), } }
// new websocket connection wrapper func NewWSConnection(wsConn *websocket.Conn) *WSConnection { return &WSConnection{ id: wsConn.RemoteAddr().String(), wsConn: wsConn, writeChan: make(chan WSResponse, WriteChanBufferSize), // buffered. we keep track when its full quitChan: make(chan struct{}), } }
/* DefaultonUnsubscribeFactory will return functions that just log the unsubscribing uri */ func (self *Router) DefaultOnUnsubscribeFactory(ws *websocket.Conn, principal string) func(s *Subscription, reason interface{}) { return func(s *Subscription, reason interface{}) { self.Debugf("%v\t%v\t%v\t%v\t[unsubscribing]", ws.RemoteAddr(), principal, s.Name(), reason) if self.LogLevel > wsubs.TraceLevel { self.Tracef("%s", debug.Stack()) } } }
func newConnection(conn *ws.Conn) *connection { c := &connection{ conn: conn, ch: make(chan map[string]*string, 10), } c.listener = statemanager.NewListener(fmt.Sprintf("websocket(%v)", conn.RemoteAddr()), c.processUpdates) return c }
func NewWebsocketSink(appId string, givenLogger *gosteno.Logger, ws *websocket.Conn, keepAliveInterval time.Duration, wsMessageBufferSize uint) Sink { return &WebsocketSink{ logger: givenLogger, appId: appId, ws: ws, clientAddress: ws.RemoteAddr(), keepAliveInterval: keepAliveInterval, wsMessageBufferSize: wsMessageBufferSize, } }
func (c *Chat) Message(msg *Incoming, _ *nothing, ws *websocket.Conn) error { log.Printf("recv from %v:%#v\n", ws.RemoteAddr(), msg) c.broadcast.Broadcast <- Outgoing{ Time: time.Now(), From: msg.From, Message: msg.Message, } return nil }
func sendMessagesToWebsocket(logMessages []*logmessage.Message, ws *websocket.Conn, logger *gosteno.Logger) { for _, message := range logMessages { err := ws.WriteMessage(websocket.BinaryMessage, message.GetRawMessage()) if err != nil { logger.Debugf("Dump Sink %s: Error when trying to send data to sink %s. Requesting close. Err: %v", ws.RemoteAddr(), err) } else { logger.Debugf("Dump Sink %s: Successfully sent data", ws.RemoteAddr()) } } }
// new websocket connection wrapper func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw events.EventSwitch) *wsConnection { wsc := &wsConnection{ remoteAddr: baseConn.RemoteAddr().String(), baseConn: baseConn, writeChan: make(chan RPCResponse, writeChanCapacity), // error when full. funcMap: funcMap, evsw: evsw, } wsc.QuitService = *NewQuitService(log, "wsConnection", wsc) return wsc }
func NewCcusConn(ws *websocket.Conn, cc_in chan updateInfo) *ccusConn { log.Printf("ws[%s]:new connect %s", ws.RemoteAddr(), ws.LocalAddr()) ws.SetReadDeadline(time.Now().Add(pongWait)) ws.SetWriteDeadline(time.Now().Add(writeWait)) pc := &ccusConn{} pc.ws = ws pc.cc_in = cc_in go pc.receiver() return pc }
// Creates a new Connection func newConnection(ws *websocket.Conn, o *Options) *Connection { return &Connection{ o, ws, ws.RemoteAddr(), make(chan error, 1), make(chan int, 1), make(chan bool, 3), make(chan error, 1), make(chan bool, 1), nil, } }
func makeWebsocketListener(ws *websocket.Conn, done chan struct{}) deploy.Listener { return func(logs <-chan deploy.LogEntry) { defer func() { done <- struct{}{} }() for entry := range logs { err := ws.WriteJSON(entry) if err != nil { log.Printf("error writing to websocket: %s. (remote address=%s)\n", err, ws.RemoteAddr()) return } } } }
func PubSubHandler(conn *websocket.Conn, pubsubClient *redis.PubSub) { for { msgi, err := pubsubClient.ReceiveMessage() if err != nil { return } switch msg := interface{}(msgi).(type) { case *redis.Message: var json_blob interface{} bytes_blob := []byte(msg.Payload) if err := json.Unmarshal(bytes_blob, &json_blob); err != nil { logger.Printf("[%s][error] failed to parse JSON %v, because %v", conn.RemoteAddr(), msg.Payload, err) continue } if err := conn.WriteJSON(json_blob); err != nil { logger.Printf("[%s][error] failed to send JSON, because %v", conn.RemoteAddr(), err) conn.Close() return } logger.Printf("[%s][send] OK", conn.RemoteAddr()) default: logger.Printf("[%s][error] Unkown message: %s", conn.RemoteAddr(), msg) return } } }
func newPlayer(ws *websocket.Conn) *player { self := &player{} self.ws = ws // Bot players do not use a websocket. if self.ws != nil { self.output = make(chan []byte, 256) //self.compressor = backstream.NewWriter(self, 0) self.addr = ws.RemoteAddr() } else { self.output = nil } // Creating controller. self.control = NewControl() self.speedFactor = 1.0 // Creating a ship. self.Ship = ship.NewShip() self.Ship.Entity.Kind = (1 + rand.Intn(8)) switch self.Ship.Entity.Kind { case 1, 2, 3, 4: self.Ship.Entity.Width = 80 self.Ship.Entity.Height = 120 case 5, 6, 7, 8: self.Ship.Entity.Width = 80 self.Ship.Entity.Height = 110 } self.Ship.Entity.Model = fmt.Sprintf("ship-%d", self.Ship.Entity.Kind) self.hitValue = 2 self.Life = playerMaxLife self.bulletType = BULLET_1X self.shootTicks = 0 // Default values. self.SetSpeed(0) self.SetDirection(0, -1) self.SetPosition(0, 0) return self }
func sendMessagesToWebsocket(envelopes []*events.Envelope, websocketConnection *gorilla.Conn, logger *gosteno.Logger) { for _, messageEnvelope := range envelopes { envelopeBytes, err := proto.Marshal(messageEnvelope) if err != nil { logger.Errorf("Websocket Server %s: Error marshalling %s envelope from origin %s: %s", websocketConnection.RemoteAddr(), messageEnvelope.GetEventType().String(), messageEnvelope.GetOrigin(), err.Error()) continue } err = websocketConnection.WriteMessage(gorilla.BinaryMessage, envelopeBytes) if err != nil { logger.Errorf("Websocket Server %s: Error when trying to send data to sink %s. Err: %v", websocketConnection.RemoteAddr(), err) } else { logger.Debugf("Websocket Server %s: Successfully sent data", websocketConnection.RemoteAddr()) } } }
func (h *websocketHandler) runWebsocketUntilClosed(ws *websocket.Conn) (closeCode int, closeMessage string) { keepAliveExpired := make(chan struct{}) clientWentAway := make(chan struct{}) // TODO: remove this loop (but keep ws.ReadMessage()) once we retire support in the cli for old style keep alives go func() { for { _, _, err := ws.ReadMessage() if err != nil { close(clientWentAway) h.logger.Debugf("websocket handler: connection from %s was closed", ws.RemoteAddr().String()) return } } }() go func() { server.NewKeepAlive(ws, h.keepAlive).Run() close(keepAliveExpired) h.logger.Debugf("websocket handler: Connection from %s timed out", ws.RemoteAddr().String()) }() closeCode = websocket.CloseNormalClosure closeMessage = "" for { select { case <-clientWentAway: return case <-keepAliveExpired: closeCode = websocket.ClosePolicyViolation closeMessage = "Client did not respond to ping before keep-alive timeout expired." return case message, ok := <-h.messages: if !ok { h.logger.Debug("websocket handler: messages channel was closed") return } err := ws.WriteMessage(websocket.BinaryMessage, message) if err != nil { h.logger.Debugf("websocket handler: Error writing to websocket: %s", err.Error()) return } } } }
func NewConnection(ws *websocket.Conn) (*connection, error) { var err error ret := &connection{ws: ws} err = ws.WriteJSON(&MyNode) if err == nil { err = ws.ReadJSON(&ret.node) } if err != nil { return nil, err } ret.name = fmt.Sprintf("%s -> %s (%s)", ws.LocalAddr(), ws.RemoteAddr(), ret.node) ret.sendChan = make(chan interface{}, 1) go ret.sendLoop() return ret, nil }
func cleanUpSocket(conn *websocket.Conn) { Info.Println("Cleaning up connection from %s", conn.RemoteAddr()) Info.Println(len(gameObjects)) clientId := connections[conn] clientData := clientIdMap[clientId] for id, _ := range clientData.GameObjects { Trace.Println("deleting from gameObjects map, id: %s", id) // TODO: Need to delete all references to this object...Idk how to best // do that. delete(gameObjects, id) delete(playerObjects, id) delete(physicsComponents, id) } delete(clientIdMap, clientData.ClientId) delete(connections, conn) Info.Println(len(gameObjects)) conn.Close() printGameObjectMap() }
func (this *subServer) wsWritePump(clientGone chan struct{}, ws *websocket.Conn, fetcher store.Fetcher) { defer fetcher.Close() var err error for { select { case msg := <-fetcher.Messages(): ws.SetWriteDeadline(time.Now().Add(time.Second * 10)) // FIXME because of buffer, client recv 10, but kateway written 100, then // client quit... if err = ws.WriteMessage(websocket.BinaryMessage, msg.Value); err != nil { log.Error("%s: %v", ws.RemoteAddr(), err) return } if err = fetcher.CommitUpto(msg); err != nil { log.Error(err) // TODO add more ctx } case err = <-fetcher.Errors(): // TODO log.Error(err) case <-this.timer.After(this.wsPongWait / 3): ws.SetWriteDeadline(time.Now().Add(time.Second * 10)) if err = ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil { log.Error("%s: %v", ws.RemoteAddr(), err) return } case <-this.gw.shutdownCh: return case <-clientGone: return } } }
func (this *subServer) wsReadPump(clientGone chan struct{}, ws *websocket.Conn) { ws.SetReadLimit(this.wsReadLimit) ws.SetReadDeadline(time.Now().Add(this.wsPongWait)) ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(this.wsPongWait)) return nil }) // if kateway shutdown while there are open ws conns, the shutdown will // wait 1m: this.subServer.wsPongWait for { _, message, err := ws.ReadMessage() if err != nil { if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) { log.Warn("%s: %v", ws.RemoteAddr(), err) } else { log.Debug("%s: %v", ws.RemoteAddr(), err) } close(clientGone) break } log.Debug("ws[%s] read: %s", ws.RemoteAddr(), string(message)) } }
func messageCLI(ws *websocket.Conn, vault *client) MessageHandler { return func(data map[string]interface{}) error { var req messageCLIRequest if err := mapstructure.WeakDecode(data, &req); err != nil { return ws.WriteJSON(&messageCLIResponse{ ExitCode: 1, Stderr: fmt.Sprintf("error decoding command: %s", err), }) } args, err := shellwords.Parse(req.Command) if err != nil { return ws.WriteJSON(&messageCLIResponse{ ExitCode: 1, Stderr: fmt.Sprintf("error parsing command: %s", err), }) } if len(args) == 0 || args[0] != "vault" { command := "<empty>" if len(args) > 0 { command = args[0] } return ws.WriteJSON(&messageCLIResponse{ ExitCode: 127, Stderr: fmt.Sprintf("invalid command: %s", command), }) } log.Printf("[DEBUG] %s: executing: %v", ws.RemoteAddr(), args) code, stdout, stderr := vault.CLI(args[1:]) return ws.WriteJSON(&messageCLIResponse{ ExitCode: code, Stdout: stdout, Stderr: stderr, }) } }
func sendMessagesToWebsocket(endpoint string, envelopes []*events.Envelope, websocketConnection *gorilla.Conn, batcher Batcher, logger *gosteno.Logger) { for _, messageEnvelope := range envelopes { envelopeBytes, err := proto.Marshal(messageEnvelope) if err != nil { logger.Errorf("Websocket Server %s: Error marshalling %s envelope from origin %s: %s", websocketConnection.RemoteAddr(), messageEnvelope.GetEventType().String(), messageEnvelope.GetOrigin(), err.Error()) continue } err = websocketConnection.WriteMessage(gorilla.BinaryMessage, envelopeBytes) if err != nil { logger.Errorf("Websocket Server %s: Error when trying to send data to sink %s. Err: %v", websocketConnection.RemoteAddr(), err) continue } batcher.BatchCounter("sentEnvelopes"). SetTag("protocol", "ws"). SetTag("event_type", messageEnvelope.GetEventType().String()). SetTag("endpoint", endpoint). Increment() logger.Debugf("Websocket Server %s: Successfully sent data", websocketConnection.RemoteAddr()) } }
func (l *listener) handler(ws *websocket.Conn, req *http.Request) { l.lock.Lock() if !l.running { ws.Close() l.lock.Unlock() return } if ws.Subprotocol() != l.proto.Name()+".sp.nanomsg.org" { ws.Close() l.lock.Unlock() return } w := &wsPipe{ws: ws, addr: l.addr, proto: l.proto, open: true} w.dtype = websocket.BinaryMessage w.iswss = l.iswss w.ws.SetReadLimit(int64(l.maxrx)) w.props = make(map[string]interface{}) w.props[mangos.PropLocalAddr] = ws.LocalAddr() w.props[mangos.PropRemoteAddr] = ws.RemoteAddr() if req.TLS != nil { w.props[mangos.PropTLSConnState] = *req.TLS } w.wg.Add(1) l.pending = append(l.pending, w) l.cv.Broadcast() l.lock.Unlock() // We must not return before the socket is closed, because // our caller will close the websocket on our return. w.wg.Wait() }
func (wp websocketProxy) Copy(dst, src *websocket.Conn) { typ, message, err := src.ReadMessage() for err == nil { dst.WriteMessage(typ, message) typ, message, err = src.ReadMessage() } if err != io.EOF { logger.WithFields(logrus.Fields{ "error": err, "source": src.RemoteAddr(), "destination": dst.RemoteAddr(), }).Error("Error while proxying WS data.") } else { logger.WithFields(logrus.Fields{ "source": src.RemoteAddr(), "destination": dst.RemoteAddr(), }).Debug("Source closed connection during WS proxying.") } }
func conn(ws *websocket.Conn) { c := &Connection{send: make(chan []byte, sendChanSize), ws: ws} os := onConnFun() c.os = os if os != nil { go c.writePump() os.OnGwsrpcOpen(c, ws.RemoteAddr().String()) c.readPump() os.OnGwsrpcClose() } ws.Close() }
// XXX: pass this as a log context (gorilla) object func getWsConnId(r *http.Request, ws *websocket.Conn) string { return fmt.Sprintf("ws:/%v %v (subprotocol %+v)", r.URL.Path, ws.RemoteAddr(), ws.Subprotocol()) }
/* DefaultEventLoggerFactory will return functions that just log the bubbling event */ func (self *Router) DefaultEventLoggerFactory(ws *websocket.Conn, principal string) func(name string, i interface{}, op string, dur time.Duration) { return func(name string, i interface{}, op string, dur time.Duration) { self.Debugf("%v\t%v\t%v\t%v\t%v ->", ws.RemoteAddr(), principal, op, name, dur) } }
func (r *Handler) serveWS(conn *websocket.Conn) { handshake := struct { Protocol string ObjectVersions objectVersions }{} //first message is the rt handshake if err := conn.ReadJSON(&handshake); err != nil { conn.WriteMessage(websocket.TextMessage, []byte("Invalid rt handshake")) conn.Close() return } if handshake.Protocol != proto { conn.WriteMessage(websocket.TextMessage, []byte("Invalid rt protocol version")) conn.Close() return } //ready u := &User{ ID: conn.RemoteAddr().String(), Connected: true, uptime: time.Now(), conn: conn, versions: handshake.ObjectVersions, pending: []*update{}, } //add user and subscribe to each obj r.mut.Lock() for k := range u.versions { if _, ok := r.objs[k]; !ok { conn.WriteMessage(websocket.TextMessage, []byte("missing object: "+k)) r.mut.Unlock() return } } r.users[u.ID] = u if r.watchingUsers { r.userEvents <- u } for k := range u.versions { obj := r.objs[k] obj.subscribers[u.ID] = u //create initial update u.pending = append(u.pending, &update{ Key: k, Version: obj.version, Data: obj.bytes, }) obj.Update() } r.mut.Unlock() //loop here during connection for { //msgType, msgBytes, err _, _, err := conn.ReadMessage() if err != nil { break } //TODO(jpillora): allow changing of subscriptions } conn.Close() //ensure closed u.Connected = false //remove user and unsubscribe to each obj r.mut.Lock() delete(r.users, u.ID) if r.watchingUsers { r.userEvents <- u } for k := range u.versions { obj := r.objs[k] delete(obj.subscribers, u.ID) } r.mut.Unlock() //disconnected }
func newClient(socket *websocket.Conn) *client { log.Printf("Creating New Client: %s", socket.RemoteAddr()) return &client{socket, "", make(chan *clientOutMessage, messageBufferSize)} }
func send(conn *websocket.Conn, number int, unsub chan<- *websocket.Conn) { if err := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("%02x", number))); err != nil { log.Printf("%s: %s", conn.RemoteAddr(), err) unsub <- conn } }