func handleChangeNotification(socket *websocket.Conn, userID string, err chan string) { res, errr := r.Table("notifications"). Filter(r.Row.Field("UserId"). Eq(userID)). Changes(). Run(api.Sess) var value HandleChange if errr != nil { err <- errr.Error() } for res.Next(&value) { var notif api.Notification var simpleNotif api.WebSocketNotification mapstructure.Decode(value.NewVal, ¬if) if notif.Id == "" { mapstructure.Decode(value.OldVal, ¬if) simpleNotif.OldVal = true } else { simpleNotif.OldVal = false } simpleNotif.Title = "notification" simpleNotif.Type = notif.Type simpleNotif.Name = notif.Name simpleNotif.UserIdFrom = notif.UserIdFrom simpleNotif.IdLink = notif.IdLink simpleNotif.CreatedAt = notif.CreatedAt errr := socket.WriteJSON(simpleNotif) if errr != nil { err <- errr.Error() } } }
func streamResults(sock *websocket.Conn, params searchParams, limit int) { start := time.Now() count := 0 results := make(chan searchResult) control := make(chan struct{}, 1) go find(results, control, params) for { res, ok := <-results if !ok { log.Printf("Finished request in %v\n", time.Since(start)) return } count++ log.Printf("Found result #%v after %v\n", count, time.Since(start)) err := sock.WriteJSON(res) if err != nil { log.Printf("Error while writing result: %v\n", err) control <- struct{}{} return } if count >= limit { log.Printf("Finished request after hitting limit in %v\n", time.Since(start)) control <- struct{}{} return } } }
func subChannelEvent(c *websocket.Conn, channel string) { subChan := subChannel{Event: "addChannel", Channel: channel} err := c.WriteJSON(subChan) if err != nil { log.Printf("sub channel %s err :%s", channel, err) } }
// 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 } } } }
func messagePing(ws *websocket.Conn, vault *client) MessageHandler { return func(data map[string]interface{}) error { return ws.WriteJSON(&messagePingResponse{ Pong: true, }) } }
func streamStatus(sock *websocket.Conn) { installed := installedPacks() filteredInstalled := []shared.Pack{} available := availablePacks() loopinstalled: for _, ip := range installed { for ai, ap := range available { if ip.Installing && ip.File == ap.File { available[ai].Installing = true continue loopinstalled } } filteredInstalled = append(filteredInstalled, ip) } info := StatusInfo{ Packs: PackInfo{ Installed: filteredInstalled, Available: available, }, Version: global.buildVersion, } err := sock.WriteJSON(controlResponse{Typ: "StatusResponse", Data: info}) if err != nil { log.Printf("Error while writing status info: %v\n", err) return } }
func clientGetRequest(wsConn *websocket.Conn, action string) { messageMap := make(map[string]interface{}) messageMap["action"] = action wsConn.WriteJSON(messageMap) }
func clientDiffRequest(wsConn *websocket.Conn, session *mgo.Session) { // init client_diff_request response_map := make(map[string]interface{}) response_map["action"] = "client_diff_request" // find syncable object uuids cb := session.DB("landline").C("SyncableObjects") var m_result []map[string]interface{} err := cb.Find(bson.M{}).All(&m_result) if err != nil { log.Println(err) } else { // objects that the clients knows, but the server may not object_uuids := make(map[string]interface{}) // loop results for u, result := range m_result { _ = u object_uuids[result["uuid"].(string)] = result["time_modified_since_creation"] } response_map["object_uuids"] = object_uuids // send it over websocket wsConn.WriteJSON(response_map) log.Println("Wrote message:") jsonString, _ := json.Marshal(response_map) log.Println(string(jsonString)) } }
func commandUnsubscribeFromTreeState(conn *websocket.Conn, id string, message map[string]interface{}) { name, ok := stringProp(message, "name") if !ok { sendErrorMessage(conn, "No \"name\" property specified or not a string in UNSUBSCRIBE_FROM_TREE_STATE message") return } globalLock.Lock() defer globalLock.Unlock() _, ok = broadcasts[name] if !ok { sendErrorMessage(conn, fmt.Sprintf("Unknown broadcast: %v", name)) return } listeners, ok := treeStateListeners[name] if !ok { return } delete(*listeners, id) conn.WriteJSON(struct { Command string `json:"command"` }{ "UNSUBSCRIBE_FROM_TREE_STATE_RECEIVED", }) }
func sendErrorMessage(conn *websocket.Conn, message string) { log.Println(message) conn.WriteJSON(struct { Command string `json:"command"` Message string `json:"message"` }{"ERROR", message}) }
func commandSubscribeToTreeState(conn *websocket.Conn, id string, message map[string]interface{}) { name, ok := stringProp(message, "name") if !ok { sendErrorMessage(conn, "No \"name\" property specified or not a string in SUBSCRIBE_TO_TREE_STATE message") return } globalLock.Lock() defer globalLock.Unlock() _, ok = broadcasts[name] if !ok { sendErrorMessage(conn, fmt.Sprintf("Unknown broadcast: %v", name)) return } listeners, ok := treeStateListeners[name] if !ok { listeners = &map[string]*websocket.Conn{} treeStateListeners[name] = listeners } (*listeners)[id] = conn conn.WriteJSON(struct { Command string `json:"command"` }{ "SUBSCRIBE_TO_TREE_STATE_RECEIVED", }) notifyTreeListeners(name) }
func commandEndBroadcast(conn *websocket.Conn, id string, message map[string]interface{}) { name, ok := stringProp(message, "name") if !ok { sendErrorMessage(conn, "No \"name\" property specified or not a string in END_BROADCAST message") return } globalLock.Lock() defer globalLock.Unlock() broadcast, ok := broadcasts[name] if !ok { sendErrorMessage(conn, fmt.Sprintf("Broadcast \"%v\" does not exist", name)) return } if broadcast.id != id { sendErrorMessage(conn, fmt.Sprintf("Peer \"%v\" did not start broadcast \"%v\"", id, name)) return } endBroadcast(name, broadcast) conn.WriteJSON(struct { Command string `json:"command"` Name string `json:"name"` }{ "END_BROADCAST_RECEIVED", name, }) }
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 } } }
// NOTE :: When a guild voice server changes how do we shut this down // properly, so a new connection can be setup without fuss? // // wsHeartbeat sends regular heartbeats to voice Discord so it knows the client // is still connected. If you do not send these heartbeats Discord will // disconnect the websocket connection after a few seconds. func (v *VoiceConnection) wsHeartbeat(wsConn *websocket.Conn, close <-chan struct{}, i time.Duration) { if close == nil || wsConn == nil { return } var err error ticker := time.NewTicker(i * time.Millisecond) for { v.log(LogDebug, "sending heartbeat packet") v.wsMutex.Lock() err = wsConn.WriteJSON(voiceHeartbeatOp{3, int(time.Now().Unix())}) v.wsMutex.Unlock() if err != nil { v.log(LogError, "error sending heartbeat to voice endpoint %s, %s", v.endpoint, err) return } select { case <-ticker.C: // continue loop and send heartbeat case <-close: return } } }
// heartbeat sends regular heartbeats to Beam so it knows the client // is still connected. If you do not send these heartbeats Beam will // disconnect the websocket connection after a few seconds. func (s *Session) heartbeat(wsConn *websocket.Conn, listening <-chan interface{}, i time.Duration) { if listening == nil || wsConn == nil { return } s.Lock() s.DataReady = true s.Unlock() var err error ticker := time.NewTicker(i * time.Millisecond) for { err = wsConn.WriteJSON(heartbeatOp{1, int(time.Now().Unix())}) if err != nil { fmt.Println("Error sending heartbeat:", err) return } select { case <-ticker.C: // continue loop and send heartbeat case <-listening: return } } }
func loadLatestSales(websocketConnection *websocket.Conn) { results, err := r.Table("analytics").Filter(M{ "type": "sale", }).OrderBy( r.Desc(r.Row.Field("data").Field("date")), ).Limit(10).Map(func(row r.Term) interface{} { return row.Field("data") }).Run(rethinkSession) if err != nil { log.Printf("error loadLatestSales: %q", err) } defer results.Close() var latestSales []interface{} err = results.All(&latestSales) if err != nil { log.Println(err) return } log.Printf("sending latest %d sales\n", len(latestSales)) socketOutgoingMessage := &SocketOutgoingMessage{ Function: "loadLatestSales", Data: M{ "type": "sale", "data": latestSales, }, } err = websocketConnection.WriteJSON(socketOutgoingMessage) if err != nil { log.Println(err) } }
func (c Discord) WSInit(con *websocket.Conn, msgChan chan WSMsg) { //send init on wire p := Properties{ OS: "DiscordBot", Browser: "discord.go", Device: "console", Referrer: "", ReferringDomain: "", } msgData := INIT{ Token: c.Token, Version: 3, // hard-coded so changes will only happen when coded in Properties: &p, } msg := WSMsg{ Op: 2, Data: msgData, } j, _ := json.Marshal(msg) fmt.Printf("msgSentInit: `%s`\n", j) /* if err := con.WriteMessage(1, j); err != nil { fmt.Println("wsInit:",err) } */ err := con.WriteJSON(msg) if err != nil { fmt.Println("wsInit:", err) } }
func wsSend(con *websocket.Conn, msgSend chan WSMsg, done, readDone, stopWS chan int) { defer fmt.Println("wsSend: goroutine stopped") seq := 1 for { select { case <-stopWS: stopSend(con, done) return case <-readDone: stopSend(con, done) return case nextMsg, ok := <-msgSend: if ok { //send the message on the channel to the connection nextMsg.Seq = seq seq++ fmt.Println("wsSend: sending msg", nextMsg.Type) j, _ := json.Marshal(nextMsg) fmt.Printf("wsSend: msg sent: `%s`\n", j) if err := con.WriteJSON(&nextMsg); err != nil { fmt.Println("wsSend:", err) } } } } }
// Handle open Subscriber. func onOpen(conn *websocket.Conn, w http.ResponseWriter, r *http.Request, sessionID string, app *app) websocketError { params := r.URL.Query() p := params.Get("protocol") protocol, err := strconv.Atoi(p) if err != nil { return newInvalidVersionStringFormatError() } switch { case strings.TrimSpace(p) == "": return newNoProtocolVersionSuppliedError() case protocol != SUPPORTED_PROTOCOL_VERSION: return newUnsupportedProtocolVersionError() case app.ApplicationDisabled: return newApplicationDisabledError() case r.TLS != nil: if app.OnlySSL { return newApplicationOnlyAccepsSSLError() } } // Create the new Subscriber connection := newConnection(sessionID, conn) app.Connect(connection) // Everything went fine. Huhu. if err := conn.WriteJSON(newConnectionEstablishedEvent(connection.SocketID)); err != nil { return newGenericReconnectImmediatelyError() } return nil }
func hostState(msg Message, gameId string, playerId int, gs GameService, ws *websocket.Conn, db *gorp.DbMap, log *log.Logger) error { log.Printf("Got state change request from host: %v", msg["state"]) game, _, err := gs.GetGame(db, gameId, playerId) if err != nil { log.Printf("%#v", err) return err } // TODO: check to make sure this is a valid state game.State = msg["state"].(string) var board *TicTacToe_Board if game.State == "start" { board = &TicTacToe_Board{Game: gameId} log.Printf("Setting up starting objects") // we are starting a game, so insert a new board err = board.setBoard([]int{0, 0, 0, 0, 0, 0, 0, 0, 0}) if err != nil { log.Printf("Unable to set game board: %#v", err) return err } log.Printf("Inserting board: %#v", board) err = db.Insert(board) if err != nil { log.Printf("Couldn't insert board: %#v", err) return err } } else { board, err = getBoard(gameId, db) if err != nil { log.Printf("Unable to get board: %#v", err) return err } } log.Printf("Updating game state to %#v", game.State) count, err := db.Update(game) if err != nil || count == 0 { log.Printf("Unable to change game state: %v", err) return err } niceBoard, err := board.getBoard() if err != nil { log.Printf("Error getting board: %#v", board) return err } log.Printf("Sending state %v to all players", msg["state"]) gs.Broadcast(gameId, Message{ "type": "update", "board": niceBoard, "state": "start", }) log.Printf("Updating UI") ws.WriteJSON(Message{ "type": "update", "board": niceBoard, "state": "start", }) return nil }
// Handle sending messages to the front-end via websockets func wsWriter(ws *websocket.Conn, msgs chan wsMessage) { for { msg := <-msgs ws.WriteJSON(msg) } }
// Emit an Websocket ErrorEvent func emitWSError(err websocketError, conn *websocket.Conn) { event := newErrorEvent(err.GetCode(), err.GetMsg()) if err := conn.WriteJSON(event); err != nil { log.Error(err) } }
// Registers the connection from to the intools engine func (appClient *AppClient) Register(conn *websocket.Conn) { // Add the client to the connected clients logs.Debug.Printf("Connection event from client") var client = &Client{ Socket: conn, GroupIds: []string{}, } logs.Debug.Printf("clients before %v", appClient.Clients) appClient.Clients[conn] = client // appClient.Clients = append(appClient.Clients, client) logs.Debug.Printf("clients %v", appClient.Clients) // Send ack message := Message{ Command: "connected", Data: nil, } conn.WriteJSON(message) // Handles events from client Events: for { var message Message err := conn.ReadJSON(&message) if err != nil { switch err.(type) { case *websocket.CloseError: logs.Debug.Printf("Websocket %p is deconnected. Removing from clients", conn) delete(appclient.Clients, conn) logs.Debug.Printf("Clients are now %v", appClient.Clients) break Events default: logs.Error.Printf("Error while reading json message : %s", err) continue Events } } logs.Debug.Printf("Message %v", message) switch message.Command { case "register-group": // Handles group registering for the client client.GroupIds = append(client.GroupIds, message.Data["groupId"].(string)) logs.Debug.Printf("Registered group %s for client %p", message.Data["groupId"], client) case "unregister-group": // Handles group unregistering for the client i := utils.IndexOf(client.GroupIds, message.Data["groupId"].(string)) if i != -1 { client.GroupIds = append(client.GroupIds[:i], client.GroupIds[i+1:]...) logs.Debug.Printf("Unregistered group %s for client %p", message.Data["groupId"], client) } } logs.Debug.Printf("Registered groups for client %p are now : %s", client, client.GroupIds) } }
// unsubscribe from an event func unsubscribe(t *testing.T, con *websocket.Conn, eventid string) { err := con.WriteJSON(rpctypes.WSRequest{ Type: "unsubscribe", Event: eventid, }) if err != nil { t.Fatal(err) } }
func sendErrorNotification(c *websocket.Conn, err error) error { return c.WriteJSON(&struct { MsgType string `json:"msg-type"` Message string `json:"message"` }{ "error", err.Error(), }) }
func sendPostSimilarities(c *websocket.Conn, s map[int64]int64) error { return c.WriteJSON(&struct { MsgType string `json:"msg-type"` SimilarityMap map[int64]int64 `json:"similarities"` }{ "post-similarities", s, }) }
func sendBlogsLikingPostData(c *websocket.Conn, blogs []string) error { return c.WriteJSON(&struct { MsgType string `json:"msg-type"` Blogs []string `json:"blogs"` }{ "blogs-liking-post", blogs, }) }
func sendPostsData(c *websocket.Conn, pd map[int64]tumblr.Post) error { return c.WriteJSON(&struct { MsgType string `json:"msg-type"` PostData map[int64]tumblr.Post `json:"posts-data"` }{ "posts-data", pd, }) }
func PlayerInit(playerId int, gameId string, gs GameService, ws *websocket.Conn, db *gorp.DbMap) error { log.Printf("Player is connected: %#v", playerId) game, _, err := gs.GetGame(db, gameId, playerId) if err != nil { log.Printf("Couldn't get player and/or game") return err } if game.State == "start" { log.Printf("Player %#v rejoining game in play", playerId) board, err := getBoard(gameId, db) if err != nil { log.Printf("Can't get TTT board: %#v", err) return err } log.Printf("Got board, getting nicer one: %#v", board) niceBoard, err := board.getBoard() if err != nil { log.Printf("Unable to get nice board: %#v", err) return err } log.Printf("Got board for player %#v: %#v", playerId, board) // There may not be a board yet so just try and send it ws.WriteJSON(Message{ "type": "update", "state": game.State, "board": niceBoard, }) } else { ws.WriteJSON(Message{ "type": "update", "state": game.State, "board": nil, }) } // check to make sure this player has a turn row turn := TicTacToe_Turn{} err = db.SelectOne(&turn, "select * from tictactoe_turn where game=? and player=?", gameId, playerId) if err != nil { turn.Game = gameId turn.Player = playerId turn.Move = -1 err = db.Insert(&turn) if err != nil { log.Printf("Unable to insert initial turn row: %#v", err) return err } } gs.SendHost(gameId, Message{"type": "join"}) return nil }
func wsSendBeat(con *websocket.Conn, now time.Time) { beat := WSMsg{ Op: 1, Data: now.Unix(), } fmt.Println("sent beat") con.WriteJSON(beat) j, _ := json.Marshal(beat) fmt.Printf("beat: %s\n", j) }