func subscribeHandler(c *echo.Context) (err error) {
	ws := c.Socket()

	if err = websocket.JSON.Send(ws, "connected"); err != nil {
		log.Println(err)
		return
	}

	res, err := r.DB("notifications").Table("notification").Changes().Run(session)

	if err != nil {
		log.Println(err)
		return
	}

	var value interface{}

	defer res.Close()

	for res.Next(&value) {
		websocket.JSON.Send(ws, value)
	}

	return
}
Exemple #2
0
func socketHandler(c *echo.Context) error {
	var err error

	ws := c.Socket()
	conn := &Connection{Send: make(chan string, 256), WS: ws, Hub: hub}
	conn.Hub.Register <- conn
	defer func() { hub.Unregister <- conn }()
	conn.Writer()

	return err
}
Exemple #3
0
func handleCommandWS(c *echo.Context) error {
	ws := c.Socket()
	defer ws.Close()

	websocket.JSON.Send(ws, GetFileList())

	var message controlMessage
	for {
		if err := websocket.JSON.Receive(ws, &message); err != nil {
			return err
		}
		controlChan <- message
	}
}
Exemple #4
0
func (mh *MessageHandler) HandleWebSocket(c *echo.Context) error {
	ws := c.Socket()
	rawMsg := ""
	var wsID string

	for {
		if len(c.Request().Header["Sec-Websocket-Key"]) == 1 {
			wsID = c.Request().Header["Sec-Websocket-Key"][0]
		} else {
			e := "failed to pull websocket key from header"
			logrus.Errorf(e)
			return errors.New(e)
		}

		account, ok := c.Get("user").(models.Account)
		if !ok {
			logrus.Errorf("failed to get user in handle websocket")
			continue
		}

		if err := websocket.Message.Receive(ws, &rawMsg); err != nil {
			//close connection gracefully
			return c.JSON(200, Response{true, nil})
		}

		msg := models.Message{
			Connection: &models.Connection{account.AccountID, wsID, ws},
			Sender:     account,
			Raw:        []byte(rawMsg),
			Context:    c,
		}
		if err := json.Unmarshal(msg.Raw, &msg); err != nil {
			logrus.Errorf("failed to unmarshal msg %s: %s", rawMsg, err.Error())
			continue
		}

		handleAction := mh.Handlers[msg.Type]
		if handleAction == nil {
			msg.Type = "/default"
			handleAction = mh.Handlers["/default"]
		}

		logrus.Infof("%s: %+s", msg.Sender.Username, msg.Type)
		if err := handleAction(msg); err != nil {
			logrus.Errorf("failed to handle %s's action: %s.  %+v.  request: %s", msg.Sender.Username, msg.Type, err, string(msg.Raw))
		}
	}
	return nil
}
Exemple #5
0
func handleWidgetWS(c *echo.Context) error {
	ws := c.Socket()
	defer ws.Close()

	in := make(chan controlMessage, 100)
	registerClient(in)
	defer deregisterClient(in)

	for {
		message := <-in
		if err := websocket.Message.Send(ws, message.ToJSON()); err != nil {
			return err
		}
	}
}
Exemple #6
0
// establishSocketConnection will handle the live connection between the webpage
// and our game
func establishSocketConnection(c *echo.Context) error {

	// upgrade the connection to a socket
	ws := c.Socket()

	// create a new channel to receive messages
	socketChannel := make(chan string)

	// create a unique id for the socket Connection
	uniqueSocketID := uuid.New()

	// register the socket in the pool
	registerInSocketPool(uniqueSocketID, socketChannel)

	// send signals to client if something is put on the socketChanel
	// note: socketChannel will block until the next receive
	for signal := range socketChannel {

		if ws != (*websocket.Conn)(nil) {
			debug("SIGNAL: " + signal)

			// try to send the signal on the websocket
			err := websocket.Message.Send(ws, signal)

			if err != nil {
				fmt.Println("Socket connection lost")
				// remove the socket from the pool
				removeFromSocketPool(uniqueSocketID)
				// close the receiverChannel (thus also exiting the loop)
				close(socketChannel)
			}

		} else {
			debug("NO CLIENT CONNECTED: " + signal)

			// remove the socket from the pool
			removeFromSocketPool(uniqueSocketID)

			// close the receiverChannel (thus also exiting the loop)
			close(socketChannel)
		}

	}

	return nil
}
Exemple #7
0
// websockDataBots метод отправляет по вебсокету к веб-клиенту обновленную информацию по ботам при получении сигнала из канала
func (mw *ManagerWeb) websockDataBots(c *echo.Context) error {
	act := Action{}  // структура действий с массивом активных вебсокетов (добавить, удалить...)
	ws := c.Socket() // открытый вебсокет

	ch := make(chan Alarm) // канал, по сигналу которого будет отправляться обновленная информация по боту на веб-клиенту через вебсокет

	act.Command = "add" // добавить информацию по новому каналу и вебсокету
	act.Channel = ch
	mw.Sign <- act // в массив активных вебсокетов

	defer func() {
		actdef := Action{}
		actdef.Command = "del" // при закрытии вебсокета
		actdef.Channel = ch
		mw.Sign <- actdef // удалить из массива вебсокет и канал
	}()

	type List struct { // структура с данными, которые необходимо отправить на веб-клиент по вебсокету
		ID   int    `json:"id"`   // идентификатор бота
		Name string `json:"name"` // имя бота
	}

	ind := 0

	for {
		var st List // создать структуру с данными бота
		st.ID = ind
		st.Name = "name-" + strconv.Itoa(ind)

		msg, _ := json.Marshal(st)                     // сконвертировать структуру для отправки по вебсокету
		err := websocket.Message.Send(ws, string(msg)) // отправить данные веб-клиенту по вебсокету
		if err != nil {
			return err
		}

		<-ch // ждать следующего сигнала для обновления информации
		ind++
	}
	//return nil
}
Exemple #8
0
// AcceptClient upgrades connection to socket
func AcceptClient(c *echo.Context) (int, interface{}) {

	// Return if not authorized
	hauth, ok := c.Get("habloAuth").(*models.HabloAuth)
	if !ok {
		return msg.Forbidden("method requires hablo authentication")
	}

	// Load the authenticated profile
	var profile models.Profile
	log.Printf("Awaiting for Profile[ DigitsID=%d ] find", hauth.DigitsID)
	err := mangos.FindOne(constants.CProfiles, bson.M{"_id": hauth.DigitsID}, &profile)
	if err != nil {
		log.Printf("Cannot find Profile[ DigitsID=%d ]", hauth.DigitsID)
		return msg.Forbidden(err)
	}

	// Create the client
	client := &Client{
		id:      bson.NewObjectId(),
		profile: &profile,
		socket:  c.Socket(),
	}
	binds.Set(profile.ID, client)
	defer func() {
		// Unbind
		binds.Del(profile.ID)
	}()

	// Lock and pull events
	log.Println("Accepted client:", client)
	err = client.LockAndPull()
	if err != nil {
		return msg.InternalError(err)
	}

	// Clean terminate
	log.Println("Finished application:", client)
	return msg.Ok("connection finished")
}
Exemple #9
0
// handler dla WebSocketów
func wsHandler(c *echo.Context) (err error) {
	var response Geolocation
	ws := c.Socket()

	for {
		// wyplujemy wszystkie lokacje co 100ms
		for _, location := range locations {
			if err = websocket.JSON.Send(ws, location); err != nil {
				log.Println(err)
				return
			}
			time.Sleep(100 * time.Millisecond)
		}

		if err = websocket.JSON.Receive(ws, &response); err != nil {
			log.Println(err)
			return
		}

		fmt.Printf("%+v\n", response)
	}
	return
}