Esempio n. 1
1
func writer(ws *websocket.Conn) {
	pingTicker := time.NewTicker(pingPeriod)
	nodesTicker := time.NewTicker(nodesPeriod)
	defer func() {
		pingTicker.Stop()
		nodesTicker.Stop()
		ws.Close()
	}()
	for {
		select {
		case <-nodesTicker.C:

			p := []byte(fmt.Sprintf("%v", nodesH))

			if p != nil {
				ws.SetWriteDeadline(time.Now().Add(writeWait))
				if err := ws.WriteMessage(websocket.TextMessage, p); err != nil {
					return
				}
			}
		case <-pingTicker.C:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}
Esempio n. 2
0
// writer runs in a goroutine for each connected WS client. It emits all message returned by the observer.
func writer(ws *websocket.Conn, a *ApiHandlers) {
	pingTicker := time.NewTicker(pingPeriod)
	s := a.getDBSubscriber()
	jww.INFO.Println("Opened WebSocket connection.")
	defer func(is *subscriber) {
		jww.INFO.Println("Closing WebSocket connection.")
		is.quitChan <- true
		pingTicker.Stop()
		ws.Close()
	}(s)

	for {
		select {
		case msg := <-s.bufChan:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteJSON(msg); err != nil {
				return
			}
		case <-pingTicker.C:
			ws.SetWriteDeadline(time.Now().Add(writeWait))
			if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				return
			}
		}
	}
}
Esempio n. 3
0
func write(ws *websocket.Conn, mt int, payload []byte) error {
	if ws == nil {
		return errors.New("no web socket connection: ws")
	}
	ws.SetWriteDeadline(time.Now().Add(writeWait))
	return ws.WriteMessage(mt, payload)
}
Esempio n. 4
0
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
			}
		}
	}()
}
Esempio n. 5
0
func PushMsg(ws *websocket.Conn, WSWriter chan []uint8) {

	defer ws.Close()

	for {
		msg := <-WSWriter

		if msg == nil {
			continue
		}

		// write message to client
		if err := ws.WriteMessage(websocket.TextMessage, []byte(msg)); err != nil {
			log.Println("[ErrorInfo]", err.Error())
			break
		}

		if string(msg) == "bye" {
			break
		}
	}

	endChan <- true

}
Esempio n. 6
0
func WebsocketSendStream(conn *websocket.Conn, r io.Reader) chan bool {
	ch := make(chan bool)

	go func(conn *websocket.Conn, r io.Reader) {
		in := ReaderToChannel(r)
		for {
			buf, ok := <-in
			if !ok {
				break
			}

			w, err := conn.NextWriter(websocket.BinaryMessage)
			if err != nil {
				Debugf("got error getting next writer %s", err)
				break
			}

			_, err = w.Write(buf)
			w.Close()
			if err != nil {
				Debugf("got err writing %s", err)
				break
			}
		}
		closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "")
		conn.WriteMessage(websocket.CloseMessage, closeMsg)
		ch <- true
	}(conn, r)

	return ch
}
Esempio n. 7
0
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))
	}
}
Esempio n. 8
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
}
Esempio n. 9
0
func WebsocketSendStream(conn *websocket.Conn, r io.Reader) chan bool {
	ch := make(chan bool)

	if r == nil {
		close(ch)
		return ch
	}

	go func(conn *websocket.Conn, r io.Reader) {
		in := ReaderToChannel(r)
		for {
			buf, ok := <-in
			if !ok {
				break
			}

			w, err := conn.NextWriter(websocket.BinaryMessage)
			if err != nil {
				Debugf("Got error getting next writer %s", err)
				break
			}

			_, err = w.Write(buf)
			w.Close()
			if err != nil {
				Debugf("Got err writing %s", err)
				break
			}
		}
		conn.WriteMessage(websocket.TextMessage, []byte{})
		ch <- true
	}(conn, r)

	return ch
}
Esempio n. 10
0
func sendCloseMessage(t *testing.T, ws *websocket.Conn) {
	err := ws.WriteMessage(websocket.CloseMessage, []byte{})

	assert.Nil(t, err, "ws: %v", err)

	wait(10)
}
func createPlayer(conn *websocket.Conn) {
	message, _ := json.Marshal(&Message{Title: "createPlayer", Data: connections.m[conn]})

	if err := conn.WriteMessage(websocket.TextMessage, message); err != nil {
		closeConnection(conn)
	}
}
Esempio n. 12
0
// sendGameStateToConnection broadcasts the current gameState as JSON to all players
// within a connectionPair
func sendGameStateToConnection(wsConn *websocket.Conn, c *connection) {
	err := wsConn.WriteMessage(websocket.TextMessage, c.cp.gs.gameStateToJSON())
	//removing connection if updating gameState fails
	if err != nil {
		c.cp.removeConnection(c)
	}
}
Esempio n. 13
0
func runInit(c *websocket.Conn) {
	dir, _ := filepath.Abs(filepath.Dir(os.Args[0]))
	initPath := path.Join(dir, "init.cmd")
	if _, err := os.Stat(initPath); err == nil {
		file, err := os.Open(initPath)
		if err != nil {
			log.Fatal(err)
		}
		defer file.Close()

		scanner := bufio.NewScanner(file)
		for scanner.Scan() {
			line := strings.TrimSpace(scanner.Text())
			log.Println(line)
			if line != "" && !strings.HasPrefix(line, "#") {
				fmt.Println("<<", line)
				c.WriteMessage(websocket.TextMessage, []byte(line))
			}
		}

		if err := scanner.Err(); err != nil {
			log.Fatal(err)
		}
	}
}
Esempio n. 14
0
func (ws *WebSocker) writer(conn *websocket.Conn, user string, tmpl *template.Template) {
	pingTicker := time.NewTicker(pingPeriod)
	chl, chq := notifier.listen(user)
	ws.log.Println(user, "connected")
	defer func() {
		pingTicker.Stop()
		conn.Close()
		close(chq)
		ws.log.Println(user, "disconnected")
	}()
	for {
		var buf bytes.Buffer
		select {
		case p := <-chl:
			conn.SetWriteDeadline(time.Now().Add(writeWait))
			buf.Reset()
			if err := tmpl.Execute(&buf, p); err != nil {
				ws.log.Println(err)
				return
			}
			if err := conn.WriteMessage(websocket.TextMessage, buf.Bytes()); err != nil {
				return
			}
			ws.log.Println("notified:", user)
		case <-pingTicker.C:
			conn.SetWriteDeadline(time.Now().Add(writeWait))
			if err := conn.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
				ws.log.Println("ping:", err)
				return
			}
		}
	}
}
Esempio n. 15
0
func pipe_to_ws(netConn net.Conn, wsConn *websocket.Conn, protocolType int, stopChan chan int) {
	for {
		select {
		case <-stopChan:
			return
		default:
			{
				data := make([]byte, BUFFER_SIZE)
				n, err := netConn.Read(data)
				if err != nil {
					stopChan <- 1
					return
				}

				if protocolType == websocket.BinaryMessage {
					err = wsConn.WriteMessage(protocolType, data[:n])
					if err != nil {
						stopChan <- 1
						return
					}
				} else if protocolType == websocket.TextMessage {
					encodedData := []byte(base64.StdEncoding.EncodeToString(data[:n]))
					err = wsConn.WriteMessage(protocolType, encodedData)
					if err != nil {
						stopChan <- 1
						return
					}
				}
			}
		}
	}
}
Esempio n. 16
0
func newWSConn(conn *websocket.Conn, pendingWriteNum int) *WSConn {
	wsConn := new(WSConn)
	wsConn.conn = conn
	wsConn.writeChan = make(chan []byte, pendingWriteNum)

	go func() {
		for b := range wsConn.writeChan {
			if b == nil {
				break
			}

			err := conn.WriteMessage(websocket.BinaryMessage, b)
			if err != nil {
				break
			}
		}

		conn.Close()
		wsConn.Lock()
		wsConn.closeFlag = true
		wsConn.Unlock()
	}()

	return wsConn
}
Esempio n. 17
0
func (b BackendController) SendToClient(msg []byte, conn *websocket.Conn) error {
	if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
		b.CleanUpHandler(conn)
		return err
	} else {
		return nil
	}
}
Esempio n. 18
0
func (w *WebsocketController) listenForOutcomingData(connection *websocket.Conn, client *WebsocketClient) {
	for {
		received := <-client.In()
		connection.WriteMessage(websocket.TextMessage, []byte(received))

		w.logger.Println("client", client, "recieved", received)
	}
}
Esempio n. 19
0
// Write sync messages to client
func clientWriteSync(ws *websocket.Conn, payload []byte) {
	log.Println("Sending ", len(payload), "chunk.")
	err := ws.WriteMessage(websocket.BinaryMessage, payload)

	if err != nil {
		panic(err)
	}
}
func addNewPlayer(conn *websocket.Conn, oldconn *websocket.Conn) {
	if conn != oldconn {
		message, _ := json.Marshal(&Message{Title: "addPlayer", Data: connections.m[conn]})

		if err := oldconn.WriteMessage(websocket.TextMessage, message); err != nil {
			closeConnection(oldconn)
		}
	}
}
func writeEventToSubscriber(ws *websocket.Conn, c chan string) {
	for {
		event := <-c
		err := ws.WriteMessage(websocket.TextMessage, []byte(event))
		if err != nil {
			log.WithFields(log.Fields{"error": err, "msg": event}).Fatal("Could not write message.")
		}
	}
}
Esempio n. 22
0
func sendPublish(c *websocket.Conn) {
	/*
		fmt.Println("input your channels split by blank:")
		in := make([]byte, 1024)
		os.Stdin.Read(in)
	*/
	msg := "LHTTP/1.0 suubpub\r\npublish:camera_123" + "\r\n\r\nhello world"
	c.WriteMessage(websocket.TextMessage, []byte(msg))
}
Esempio n. 23
0
func sendSubscribe(c *websocket.Conn) {
	/*
		fmt.Println("input your channels split by blank:")
		in := make([]byte, 1024)
		os.Stdin.Read(in)
	*/
	msg := "LHTTP/1.0 suubpub\r\nsubscribe:cam_123" + "\r\n\r\n"
	c.WriteMessage(websocket.TextMessage, []byte(msg))
}
Esempio n. 24
0
func addOtherPlayers(conn *websocket.Conn, oldconn *websocket.Conn) {
	if conn != oldconn && connections.m[oldconn].inLobby {
		message, _ := json.Marshal(&Message{Title: "addPlayer", Player: connections.m[oldconn]})

		if err := conn.WriteMessage(websocket.TextMessage, message); err != nil {
			closeConnection(conn)
		}
	}
}
Esempio n. 25
0
func (c *connection) writer(wg *sync.WaitGroup, wsConn *websocket.Conn) {
	defer wg.Done()
	for message := range c.send {
		err := wsConn.WriteMessage(websocket.TextMessage, message)
		if err != nil {
			break
		}
	}
}
Esempio n. 26
0
func updatePlayer(conn *websocket.Conn, oldconn *websocket.Conn, data PlayerMessage) {
	if conn != oldconn {
		message, _ := json.Marshal(&data)

		if err := oldconn.WriteMessage(websocket.TextMessage, message); err != nil {
			closeConnection(oldconn)
		}
	}
}
func patchUserSource(t *testing.T, c *websocket.Conn, fileName, oldSource, newSource string) []interface{} {
	patchJson := createPatchJson(t, fileName, oldSource, newSource)
	err := c.WriteMessage(websocket.TextMessage, []byte(patchJson))
	require.Nil(t, err)
	result := make(map[string]interface{})
	err = c.ReadJSON(&result)
	require.Nil(t, err)
	return result["errors"].([]interface{})
}
Esempio n. 28
0
func sendmsg(ws *websocket.Conn, msgs ...*fayeMsg) error {
	jmsg, err := json.Marshal(msgs)
	if err != nil {
		return err
	}
	if err = ws.WriteMessage(websocket.TextMessage, jmsg); err != nil {
		return err
	}
	return nil
}
Esempio n. 29
0
File: webskt.go Progetto: mhoc/river
func WsWriter(c *websocket.Conn) {
	for {
		msg := <-SendToServer
		Display <- NewConsoleMsg(SENDING, msg)
		err := c.WriteMessage(websocket.TextMessage, []byte(msg))
		if err != nil {
			Display <- NewConsoleMsg(ERROR, err.Error())
		}
	}
}
Esempio n. 30
0
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())
		}
	}
}