本文整理匯總了Golang中github.com/gorilla/websocket.Conn.ReadJSON方法的典型用法代碼示例。如果您正苦於以下問題:Golang Conn.ReadJSON方法的具體用法?Golang Conn.ReadJSON怎麽用?Golang Conn.ReadJSON使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類github.com/gorilla/websocket.Conn
的用法示例。
在下文中一共展示了Conn.ReadJSON方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: listener
func listener(conn *websocket.Conn, ID int, field *models.Field) {
tick := time.NewTicker(5 * time.Millisecond)
for {
select {
case <-tick.C:
var req struct {
Request string `json:"request"`
Param string `json:"param"`
}
err := conn.ReadJSON(&req)
if err != nil {
//field.Remove <- ID
return
}
switch req.Request {
case "move":
dir, ok := dirMap[req.Param]
if !ok {
continue
}
wait := new(sync.WaitGroup)
wait.Add(1)
field.Change <- models.ChangeDirection{
Index: ID,
Direction: dir,
Wait: wait,
}
wait.Wait()
}
}
}
}
示例2: handleOutput
func (h *Hijacker) handleOutput(conn *websocket.Conn, pio ProcessIO) int {
var exitStatus int
for {
var output atc.HijackOutput
err := conn.ReadJSON(&output)
if err != nil {
if !websocket.IsCloseError(err) && !websocket.IsUnexpectedCloseError(err) {
fmt.Println(err)
}
break
}
if output.ExitStatus != nil {
exitStatus = *output.ExitStatus
} else if len(output.Error) > 0 {
fmt.Fprintf(os.Stderr, "%s\n", ansi.Color(output.Error, "red+b"))
exitStatus = 255
} else if len(output.Stdout) > 0 {
pio.Out.Write(output.Stdout)
} else if len(output.Stderr) > 0 {
pio.Err.Write(output.Stderr)
}
}
return exitStatus
}
示例3: Register
// 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)
}
}
示例4: pingSocket
func pingSocket(socket *websocket.Conn, err chan string) {
var v interface{}
for {
errr := socket.ReadJSON(&v)
if errr != nil {
err <- errr.Error()
}
}
}
示例5: patchUserSource
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{})
}
示例6: ReadJSON
func ReadJSON(conn *websocket.Conn) map[string]interface{} {
reply := make(map[string]interface{})
err := conn.ReadJSON(&reply)
if err != nil {
logrus.Error(err.Error())
}
return reply["data"].(map[string]interface{})
}
示例7: EmitJSONWithReply
func EmitJSONWithReply(conn *websocket.Conn, req map[string]interface{}) (map[string]interface{}, error) {
if err := conn.WriteJSON(req); err != nil {
return nil, errors.New("Error while marshing request: " + err.Error())
}
resp := make(map[string]interface{})
if err := conn.ReadJSON(&resp); err != nil {
return nil, errors.New("Error while marshing response: " + err.Error())
}
return resp["data"].(map[string]interface{}), nil
}
示例8: HandleLeafConn
func HandleLeafConn(conn *websocket.Conn) {
log.Println("Leaf connected")
for {
var packet common.Packet
if err := conn.ReadJSON(&packet); err != nil {
log.Println("Error reading leaf json: ", err)
return
}
HandlePacket(&packet, conn)
}
}
示例9: HandleConn
func HandleConn(conn *websocket.Conn) {
log.Println("Client app connected")
head.CurrentApp = conn
for {
var request Request
if err := conn.ReadJSON(&request); err != nil {
log.Println("Error reading app json: ", err)
return
}
response := HandleRequest(&request)
conn.WriteJSON(response)
}
}
示例10: processMessage
func processMessage(conn *websocket.Conn) []byte {
var tests []Test
// _ = "breakpoint"
err := conn.ReadJSON(&tests)
if err != nil {
return nil
}
tests[0].Number++
message, err := json.Marshal(&tests)
if err != nil {
return nil
}
return message
}
示例11: Join
func (chat *Chat) Join(client *websocket.Conn) {
chat.clients = append(chat.clients, client)
go func() {
for {
var message Message
err := client.ReadJSON(&message)
message.Time = time.Now()
if err != nil {
log.Println(err)
break
}
chat.incoming <- &message
log.Println("decoded message")
}
}()
}
示例12: handleConnect
func handleConnect(conn *websocket.Conn) {
player := httpPlayer{game.Black, conn}
var c commandFromClient
err := conn.ReadJSON(&c)
if err != nil {
log.Println("websocket error:", err)
return
}
switch c.Command {
case "new_game":
var args newGameArgs
if err := json.Unmarshal(c.Args, &args); err != nil {
log.Printf("bad new_game args: %s (%s)", err, string(c.Args))
return
}
game, err := game.NewGame(game.Config{
Black: player,
White: cpuPlayer,
Width: args.Width,
Height: args.Height,
Logger: os.Stderr,
})
if err != nil {
log.Printf("error creating game: %s", err)
return
}
result := game.Play()
gameOver := commandToClient{
Command: "game_over",
Args: map[string]string{
"message": fmt.Sprintf("%s (%s) is the winner!", result.Winner.Color(), result.Winner.Name()),
},
}
if err := conn.WriteJSON(gameOver); err != nil {
log.Printf("error sending game_over: %s", err)
return
}
default:
log.Printf("unknown command from http player: %s", c.Command)
}
}
示例13: readCommand
func readCommand(ws *websocket.Conn) interface{} {
var command struct {
Name string
Command json.RawMessage
}
if err := ws.ReadJSON(&command); err != nil {
return err
}
newFn := commands[command.Name]
if newFn == nil {
return errors.New("unknown command " + command.Name)
}
v := newFn()
if err := json.Unmarshal([]byte(command.Command), v); err != nil {
return err
}
return v
}
示例14: NewConnection
func NewConnection(ws *websocket.Conn) (*connection, error) {
var err error
ret := &connection{ws: ws}
err = ws.WriteJSON(&MyNode)
if err == nil {
err = ws.ReadJSON(&ret.node)
}
if err != nil {
return nil, err
}
ret.name = fmt.Sprintf("%s -> %s (%s)", ws.LocalAddr(), ws.RemoteAddr(), ret.node)
ret.sendChan = make(chan interface{}, 1)
go ret.sendLoop()
return ret, nil
}
示例15: messagesHandler
func messagesHandler(ws *websocket.Conn, ticker *time.Ticker, msg Event, c chan Event, e chan error, e2 chan error) {
ws.SetPongHandler(func(string) error {
ws.SetReadDeadline(time.Now().Add(PONG_WAIT))
return nil
})
for {
err := ws.ReadJSON(&msg)
if err != nil {
e <- err
e2 <- err
time.Sleep(4 * time.Second)
} else {
if reflect.TypeOf(msg).String() == "tutum.Event" {
c <- msg
}
}
}
}