예제 #1
1
func (w *WebsocketController) listenForIncomingData(connection *websocket.Conn, client *WebsocketClient, disconnect chan bool) {
	for {
		mt, message, err := connection.ReadMessage()

		if mt == websocket.CloseMessage {
			disconnect <- true
		}
		if _, ok := err.(*websocket.CloseError); ok {
			disconnect <- true
		}

		if err != nil {
			w.logger.Println("warning: read message error:", err)
			continue
		}
		if mt != websocket.TextMessage && mt != websocket.CloseMessage {
			w.logger.Println("warning: recieved unsupported message: ", mt, message)
			continue
		}

		if mt == websocket.TextMessage {
			w.Received() <- ReceivedData{client, message}
		}
	}
}
예제 #2
0
func (self *remoteService) run(ws *websocket.Conn) error {
	for {
		mt, msg, err := ws.ReadMessage()
		if err != nil {
			fmt.Printf("remoteService.run: %#v\n", err)
			break
		}

		if mt != websocket.BinaryMessage {
			continue
		}

		cmd := cmdResult{}
		if err := json.NewDecoder(bytes.NewReader(msg)).Decode(&cmd); err != nil {
			return err
		}

		if cmd.Id == nil {
			if err := self.handleEvent(cmd.Back, cmd.Sid, stream.Event([]byte(cmd.Data))); err != nil {
				return err
			}
		} else {
			if err := self.handleCmdRes(*cmd.Id, cmd.Data); err != nil {
				return err
			}
		}
	}
	return nil
}
예제 #3
0
func (r *RancherService) pipeLogs(container *rancherClient.Container, conn *websocket.Conn) {
	defer conn.Close()

	log_name := strings.TrimPrefix(container.Name, r.context.ProjectName+"_")
	logger := r.context.LoggerFactory.Create(log_name)

	for {
		messageType, bytes, err := conn.ReadMessage()
		if messageType != websocket.TextMessage {
			continue
		}

		if err == io.EOF {
			return
		} else if err != nil {
			logrus.Errorf("Failed to read log: %v", err)
			return
		}

		if len(bytes) <= 3 {
			continue
		}

		if bytes[len(bytes)-1] != '\n' {
			bytes = append(bytes, '\n')
		}
		message := bytes[3:]

		if "01" == string(bytes[:2]) {
			logger.Out(message)
		} else {
			logger.Err(message)
		}
	}
}
예제 #4
0
func (w *WebsocketServer) streamWebsocket(websocketSink *websocket.WebsocketSink, websocketConnection *gorilla.Conn, register func(sinks.Sink) bool, unregister func(sinks.Sink)) {
	register(websocketSink)
	defer unregister(websocketSink)

	go websocketConnection.ReadMessage()
	server.NewKeepAlive(websocketConnection, w.keepAliveInterval).Run()
}
예제 #5
0
파일: proxy.go 프로젝트: sohlich/nats-proxy
func (np *NatsProxy) activateWSProxySubject(conn *websocket.Conn, wsID string) {
	np.addToWSMapper(conn, wsID)
	np.conn.Subscribe("WS_OUT"+wsID, func(m *nats.Msg) {
		err := conn.WriteMessage(websocket.TextMessage, m.Data)
		if err != nil {
			log.Println("Error writing a message", err)
		}
	})
	go func() {
		for {
			if _, p, err := conn.ReadMessage(); err == nil {
				np.conn.Publish("WS_IN"+wsID, p)
			} else {
				np.removeFromWSMapper(conn, wsID)
				conn.Close()
				// If websocket is closed normally RFC6455
				// code 1000, then no error logged
				if !websocket.IsCloseError(err, websocket.CloseNormalClosure) {
					logWebsocketError(wsID, err)
				}
				break
			}
		}
	}()
}
예제 #6
0
파일: websocket.go 프로젝트: ray0807/goAPI
func jionToChatRoom(uname string, ws *websocket.Conn) {

	// Join chat room.
	Join(uname, ws)
	defer Leave(uname)

	// Message receive loop.
	for {
		_, p, err := ws.ReadMessage()
		if err != nil {
			return
		}
		//=======deal with chat====
		// js, err := simplejson.NewJson(p)
		// if err != nil {
		// 	panic(err.Error())
		// }
		chat := new(models.ChatBean)
		json.Unmarshal(p, chat)

		//=====================
		if chat.Type == 1 || len(chat.To) > 0 {
			publish <- newEvent(models.EVENT_CHAT, uname, string(p))
		} else {
			publish <- newEvent(models.EVENT_MESSAGE, uname, string(p))
		}

	}
}
예제 #7
0
파일: prime_wss.go 프로젝트: vachu/prime
func primeRequestMainLoop(ws *websocket.Conn) {
	msgType, msg, err := ws.ReadMessage()
	for ; err == nil && msgType == websocket.TextMessage; msgType, msg, err = ws.ReadMessage() {
		req := string(msg)
		fields := strings.Fields(req)
		if len(fields) == 0 {
			err = ws.WriteMessage(websocket.TextMessage, []byte(warnArgCount))
		} else {
			method := strings.ToUpper(fields[0])
			switch method {
			case "?":
				err = ws.WriteMessage(msgType, []byte(helpMsg))
			case "TEST":
				if len(fields) > 1 {
					err = OnTest(ws, fields[1:])
				} else {
					err = ws.WriteMessage(msgType, []byte("ERROR: nothing to test"))
				}
			case "LIST":
				err = OnList(ws, fields[1:])
			case "EXIT":
				fallthrough
			case "QUIT":
				fallthrough
			case "CLOSE":
				fmt.Fprintln(os.Stderr, "INFO: Closing Websocket...")
				break
			default:
				err = ws.WriteMessage(msgType, []byte(errorUnknownCmd))
			}
		}
		err = ws.WriteMessage(websocket.TextMessage, []byte(eotMsg))
	}
}
예제 #8
0
func pipe_to_net(netConn net.Conn, wsConn *websocket.Conn, protocolType int, stopChan chan int) {
	for {
		select {
		case <-stopChan:
			return
		default:
			{
				_, p, err := wsConn.ReadMessage()
				if err != nil {
					stopChan <- 1
					return
				}
				if protocolType == websocket.BinaryMessage {
					_, err = netConn.Write(p)
					if err != nil {
						stopChan <- 1
						return
					}
				} else if protocolType == websocket.TextMessage {
					data := make([]byte, base64.StdEncoding.DecodedLen(len(p)))
					n, err := base64.StdEncoding.Decode(data, p)
					if err != nil {
						stopChan <- 1
						return
					}
					_, err = netConn.Write(data[:n])
					if err != nil {
						stopChan <- 1
						return
					}
				}
			}
		}
	}
}
예제 #9
0
func readMessages(ws *websocket.Conn, rc chan<- error, handler Handler) (e error) {
	defer func() {
		rc <- e
	}()

	for {
		_, msg, err := ws.ReadMessage()
		if err != nil {
			return fmt.Errorf("Error reading from websocket: %s", err)
		}

		var event model.WatchEvent
		err = json.Unmarshal(msg, &event)
		if err != nil {
			return fmt.Errorf("Error parsing event: %s", err)
		}
		log.Infof("Received event: [%s]", msg)

		err = handler.Handle(event)
		if err != nil {
			return fmt.Errorf("Error handling event: %s", err)
		}

	}
}
예제 #10
0
func checkResponse(checkFor map[string]string, ws *websocket.Conn, c *check.C) string {
	for count := 0; count < 20; count++ {
		_, m, err := ws.ReadMessage()
		if err != nil {
			// ws closed
			if len(checkFor) != 0 {
				c.Fatal("Didn't find all keys before ws was closed: ", checkFor)
			}
			return ""
		}
		dst := make([]byte, base64.StdEncoding.EncodedLen(len(m)))
		_, err = base64.StdEncoding.Decode(dst, m)
		if err != nil {
			c.Fatal(err)
		}
		msg := string(dst)
		for k, _ := range checkFor {
			if strings.Contains(msg, k) {
				delete(checkFor, k)
			}
		}
		if len(checkFor) == 0 {
			return msg
		}
	}

	if len(checkFor) != 0 {
		c.Fatal("Didn't find: ", checkFor)
	}

	return ""
}
func datawsHandler(w http.ResponseWriter, r *http.Request) {
	var websocket *ws.Conn
	var upgradeerr error
	websocket, upgradeerr = upgrader.Upgrade(w, r, nil)
	if upgradeerr != nil {
		w.Write([]byte(fmt.Sprintf("Could not upgrade HTTP connection to WebSocket: %v\n", upgradeerr)))
		return
	}

	cw := ConnWrapper{
		Writing: &sync.Mutex{},
		Conn:    websocket,
	}

	websocket.SetReadLimit(MAX_REQSIZE)

	for {
		_, payload, err := websocket.ReadMessage()

		if err != nil {
			return // Most likely the connection was closed or the message was too big
		}

		uuidBytes, startTime, endTime, pw, token, echoTag, success := parseDataRequest(string(payload), &cw)

		if success {
			var loginsession *LoginSession
			if token != "" {
				loginsession = validateToken(token)
				if loginsession == nil {
					w.Write([]byte(ERROR_INVALID_TOKEN))
					return
				}
			}
			if hasPermission(loginsession, uuidBytes) {
				dr.MakeDataRequest(uuidBytes, startTime, endTime, uint8(pw), &cw)
			} else {
				cw.GetWriter().Write([]byte("[]"))
			}
		}
		if cw.CurrWriter != nil {
			cw.CurrWriter.Close()
		}

		writer, err := websocket.NextWriter(ws.TextMessage)
		if err != nil {
			fmt.Println("Could not echo tag to client")
		}

		if cw.CurrWriter != nil {
			_, err = writer.Write([]byte(echoTag))
			if err != nil {
				fmt.Println("Could not echo tag to client")
			}
			writer.Close()
		}

		cw.Writing.Unlock()
	}
}
예제 #12
0
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
		}
	}
}
예제 #13
0
파일: interactive.go 프로젝트: bnjjj/tatcli
func socketRead(c *websocket.Conn) {
	for {
		_, r, err := c.ReadMessage()
		internal.Check(err)
		fmt.Print(color(string(r)))
	}
}
예제 #14
0
파일: bot.go 프로젝트: ajm188/slack
func (bot *Bot) loop(conn *websocket.Conn) bool {
	defer conn.Close()
	for {
		messageType, bytes, err := conn.ReadMessage()
		if err != nil {
			// ReadMessage returns an error if the connection is closed
			return false
		}
		if messageType == websocket.BinaryMessage {
			continue // ignore binary messages
		}
		event, err := unpackJSON(bytes)
		if err != nil {
			log.WithFields(log.Fields{
				"raw bytes": bytes,
				"error":     err,
			}).Warn("message could not be unpacked")
			continue
		}
		log.WithFields(log.Fields{
			"event": event,
		}).Info("received event")
		eventType, ok := event["type"]
		if ok && eventType.(string) == "team_migration_started" {
			return true
		}
		wrappers := bot.handle(event)
		closeConnection := sendResponses(wrappers, conn)
		if closeConnection {
			return false
		}
	}
}
예제 #15
0
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))
	}
}
예제 #16
0
func handleWs(s Service, ws *websocket.Conn, subs map[uint32]*wsSub, slock *sync.Mutex) error {
	ch := make(chan []byte)
	defer close(ch)

	go func() {
		for {
			v, ok := <-ch
			if !ok {
				break
			}

			if err := ws.WriteMessage(websocket.BinaryMessage, v); err != nil {
				fmt.Printf("ws.WriteMessage: %#v\n", err)
				break
			}
		}
	}()

	for {
		mt, msg, err := ws.ReadMessage()
		if err != nil {
			fmt.Printf("ws.ReadMessage: %#v\n", err)
			break
		}

		if mt != websocket.BinaryMessage {
			continue
		}

		if err := iter(ch, msg, s, subs, slock); err != nil {
			return err
		}
	}
	return nil
}
예제 #17
0
파일: app.go 프로젝트: jondot/castbox
func (app *App) registerSocket(ws *websocket.Conn, hub *Hub, toHub *Hub) {
	defer hub.RemoveMember(ws)
	hub.AddMember(ws)

	app.KeepAlive()

	from := toHub.FromLabel
	to := toHub.ToLabel
	appname := app.Name

	for {
		mtype, p, err := ws.ReadMessage()
		if err != nil {
			log.Printf("%s: Connection (%s): %s", app.Name, from, err)
			break
		}

		msg := &AppMessage{Data: p,
			Mtype: mtype,
			Id:    int(atomic.AddInt32(&msgcnt, 1)),
			To:    toHub}
		log.Printf("%s: QUEUE [%d] %s -> %s (of %d) [%s]", appname, msg.Id, from, to, len(hub.Members), string(msg.Data))
		app.Channel <- msg
	}
}
예제 #18
0
func (wss *WSTraffickers) SaveConnection(accessToken string, conn *websocket.Conn) (*WSTrafficker, error) {
	_, payloadJson, err := conn.ReadMessage()
	if err != nil {
		return nil, err
	}

	var payload map[string]interface{}

	err = json.Unmarshal(payloadJson, &payload)
	if err != nil {
		return nil, err
	}

	hostnameInterface, hostnameExists := payload["Hostname"]
	if !hostnameExists {
		return nil, errors.New("Unable to establish websocket connection without Hostname payload")
	}

	wsTrafficker := NewWSTrafficker(conn)
	wsTrafficker.Hostname = hostnameInterface.(string)

	wss.ByAccessTokenHostname[accessToken+"-"+wsTrafficker.Hostname] = NewWSTrafficker(conn)

	logrus.WithFields(logrus.Fields{
		"AccessToken": accessToken,
		"Hostname":    wsTrafficker.Hostname,
	}).Info("Saved websocket connection in memory")

	return wsTrafficker, nil
}
예제 #19
0
func AddWSSink(receivedChan chan []byte, port string, path string) (*websocket.Conn, <-chan struct{}) {
	connectionDroppedChannel := make(chan struct{}, 1)

	var ws *websocket.Conn

	ip, _ := localip.LocalIP()
	fullURL := "ws://" + ip + ":" + port + path

	Eventually(func() error {
		var err error
		ws, _, err = websocket.DefaultDialer.Dial(fullURL, http.Header{})
		return err
	}, 5, 1).ShouldNot(HaveOccurred(), fmt.Sprintf("Unable to connect to server at %s.", fullURL))

	ws.SetPingHandler(func(message string) error {
		ws.WriteControl(websocket.PongMessage, []byte(message), time.Time{})
		return nil
	})

	go func() {
		for {
			_, data, err := ws.ReadMessage()
			if err != nil {
				close(connectionDroppedChannel)
				close(receivedChan)
				return
			}

			receivedChan <- data
		}

	}()

	return ws, connectionDroppedChannel
}
예제 #20
0
func wait(conn *websocket.Conn) {
	defer conn.Close()
	for {
		if _, _, err := conn.ReadMessage(); err != nil {
			break
		}
	}
}
예제 #21
0
파일: example1.go 프로젝트: baijum/slides
// START READER OMIT
func reader(ws *websocket.Conn) {
	defer ws.Close()
	for {
		if _, _, err := ws.ReadMessage(); err != nil { // HL
			break
		}
	}
}
예제 #22
0
func reader(ws *websocket.Conn) {
	defer ws.Close()
	for {
		_, _, err := ws.ReadMessage()
		if err != nil {
			log.Println(err)
		}
	}
}
예제 #23
0
/* reader reads input from the web socket connection and sends it to the master.
 * reader runs in its own goroutine.
 * If the connection closes, the reader goroutine terminates.
 */
func reader(id uint64, conn *websocket.Conn, readerResultChan chan readerResult) {
	for {
		messageType, data, err := conn.ReadMessage()
		readerResultChan <- readerResult{id, messageType, data, err}
		if err != nil {
			return
		}
	}
}
예제 #24
0
// wait for an event; do things that might trigger events, and check them when they are received
func waitForEvent(t *testing.T, con *websocket.Conn, eventid string, dieOnTimeout bool, f func(), check func(string, []byte) error) {
	// go routine to wait for webscoket msg
	gch := make(chan []byte) // good channel
	ech := make(chan error)  // error channel
	go func() {
		for {
			_, p, err := con.ReadMessage()
			if err != nil {
				ech <- err
				break
			} else {
				// if the event id isnt what we're waiting on
				// ignore it
				var response struct {
					Event string `json:"event"`
				}
				if err := json.Unmarshal(p, &response); err != nil {
					ech <- err
					break
				}
				if response.Event == eventid {
					gch <- p
					break
				}
			}
		}
	}()

	// do stuff (transactions)
	f()

	// wait for an event or 10 seconds
	ticker := time.Tick(10 * time.Second)
	select {
	case <-ticker:
		if dieOnTimeout {
			con.Close()
			t.Fatalf("%s event was not received in time", eventid)
		}
		// else that's great, we didn't hear the event
		// and we shouldn't have
	case p := <-gch:
		if dieOnTimeout {
			// message was received and expected
			// run the check
			err := check(eventid, p)
			if err != nil {
				t.Fatal(err)
			}
		} else {
			con.Close()
			t.Fatalf("%s event was not expected", eventid)
		}
	case err := <-ech:
		t.Fatal(err)
	}
}
예제 #25
0
파일: connection.go 프로젝트: LrsK/chat
func (c *connection) reader(wg *sync.WaitGroup, wsConn *websocket.Conn) {
	defer wg.Done()
	for {
		_, message, err := wsConn.ReadMessage()
		if err != nil {
			break
		}
		c.cs.broadcast <- message
	}
}
예제 #26
0
파일: webskt.go 프로젝트: mhoc/river
func WsReader(c *websocket.Conn) {
	for {
		_, msg, err := c.ReadMessage()
		if err != nil {
			Display <- NewConsoleMsg(ERROR, err.Error())
		} else {
			Display <- NewConsoleMsg(RECEIVING, string(msg))
		}
	}
}
예제 #27
0
func getTextMessage(ws *websocket.Conn) (string, error) {
	typ, msg, err := ws.ReadMessage()
	if err != nil {
		return "", fmt.Errorf("Error reading websocket message: %v", err)
	}
	if typ != websocket.TextMessage {
		return "", fmt.Errorf("Unexpected websocket message type: %v", typ)
	}
	return string(msg), nil
}
예제 #28
0
func getTextMessage(t *testing.T, ws *websocket.Conn) string {
	typ, msg, err := ws.ReadMessage()
	if err != nil {
		t.Fatal("Error reading websocket message:", err)
	}
	if typ != websocket.TextMessage {
		t.Errorf("Unexpected websocket message type: %v", typ)
	}
	return string(msg)
}
예제 #29
0
func (m *multiplexer) routeMessages(ws *websocket.Conn) {
	stopSignal := make(chan bool, 1)

	// Read messages from backend
	go func(stop chan<- bool) {
		for {
			msgType, msg, err := ws.ReadMessage()
			if err != nil {
				m.shutdown(stop)
				return
			}

			if msgType != websocket.TextMessage {
				continue
			}
			message := common.ParseMessage(string(msg))

			m.frontendMu.RLock()
			frontendChan, ok := m.frontendChans[message.Key]
			if ok {
				frontendChan <- message
			}
			m.frontendMu.RUnlock()

			if !ok && message.Type != common.Close {
				m.sendClose(message.Key)
			}
		}
	}(stopSignal)

	// Write messages to backend
	go func(stop <-chan bool) {
		ticker := time.NewTicker(time.Second * 5)
		defer ticker.Stop()
		for {
			select {
			case message, ok := <-m.messagesToBackend:
				if !ok {
					return
				}
				err := ws.WriteMessage(websocket.TextMessage, []byte(message))
				if err != nil {
					log.WithFields(log.Fields{"error": err, "msg": message}).Error("Could not write message.")
				}

			case <-ticker.C:
				ws.WriteControl(websocket.PingMessage, []byte(""), time.Now().Add(time.Second))

			case <-stop:
				return
			}
		}
	}(stopSignal)
}
예제 #30
0
파일: pipes.go 프로젝트: rnd-ua/scope
// CopyToWebsocket copies pipe data to/from a websocket.  It blocks.
func (p *pipe) CopyToWebsocket(end io.ReadWriter, conn *websocket.Conn) error {
	p.mtx.Lock()
	if p.closed {
		p.mtx.Unlock()
		return nil
	}
	p.wg.Add(1)
	p.mtx.Unlock()
	defer p.wg.Done()

	errors := make(chan error, 1)

	// Read-from-UI loop
	go func() {
		for {
			_, buf, err := conn.ReadMessage() // TODO type should be binary message
			if err != nil {
				errors <- err
				return
			}

			if _, err := end.Write(buf); err != nil {
				errors <- err
				return
			}
		}
	}()

	// Write-to-UI loop
	go func() {
		buf := make([]byte, 1024)
		for {
			n, err := end.Read(buf)
			if err != nil {
				errors <- err
				return
			}

			if err := conn.WriteMessage(websocket.BinaryMessage, buf[:n]); err != nil {
				errors <- err
				return
			}
		}
	}()

	// block until one of the goroutines exits
	// this convoluted mechanism is to ensure we only close the websocket once.
	select {
	case err := <-errors:
		return err
	case <-p.quit:
		return nil
	}
}