本文整理匯總了Golang中github.com/gorilla/websocket.Conn.WriteJSON方法的典型用法代碼示例。如果您正苦於以下問題:Golang Conn.WriteJSON方法的具體用法?Golang Conn.WriteJSON怎麽用?Golang Conn.WriteJSON使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gorilla/websocket.Conn
的用法示例。
在下文中一共展示了Conn.WriteJSON方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: handleChangeNotification
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()
}
}
}
示例2: streamResults
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
}
}
}
示例3: subChannelEvent
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)
}
}
示例4: writer
// 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
}
}
}
}
示例5: messagePing
func messagePing(ws *websocket.Conn, vault *client) MessageHandler {
return func(data map[string]interface{}) error {
return ws.WriteJSON(&messagePingResponse{
Pong: true,
})
}
}
示例6: streamStatus
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
}
}
示例7: clientGetRequest
func clientGetRequest(wsConn *websocket.Conn, action string) {
messageMap := make(map[string]interface{})
messageMap["action"] = action
wsConn.WriteJSON(messageMap)
}
示例8: clientDiffRequest
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))
}
}
示例9: commandUnsubscribeFromTreeState
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",
})
}
示例10: sendErrorMessage
func sendErrorMessage(conn *websocket.Conn, message string) {
log.Println(message)
conn.WriteJSON(struct {
Command string `json:"command"`
Message string `json:"message"`
}{"ERROR", message})
}
示例11: commandSubscribeToTreeState
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)
}
示例12: commandEndBroadcast
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,
})
}
示例13: PubSubHandler
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
}
}
}
示例14: wsHeartbeat
// 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
}
}
}
示例15: heartbeat
// 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
}
}
}