2016-04-25 42 views
0

目前,我想要使用的WebSockets進行溝通,我的代碼如下(IM使用大猩猩)圍棋的WebSockets數據gopherjs

buff := bytes.NewBuffer([]byte{}) 
binary.Write(buff, binary.LittleEndian, uint64(1)) 
binary.Write(buff, binary.LittleEndian, len(message)) 
binary.Write(buff, binary.LittleEndian, message) 
client.Write <- buff.Bytes() 

內的c.Write通道其選擇循環

case msg := <-client.Write: 
    buffer := &bytes.Buffer{} 
    err := binary.Write(buffer, binary.LittleEndian, msg) 
    if err != nil { 
     return 
    } 
    err = client.Ws.WriteMessage(websocket.BinaryMessage, buffer.Bytes()) 
    if err != nil { 
     return 
    } 
    buffer.Reset() 

和客戶端只是一個struct

type Client struct { 
    Ws  *websocket.Conn 
    Read chan []byte 
    Write chan []byte 
    Account *models.Account 
} 

成功發送的消息,我讀了這樣

b, err := conn.Read(buff) 
if err != nil { 
    utils.Log("Error while reading from socket " + err.Error()) 
    return 
} 
buffer := bytes.NewBuffer(buff[:b]) 
t, err := binary.ReadUvarint(buffer) 
utils.Log(t) 
if err != nil { 
    utils.Log("Error while reading from socket " + err.Error()) 
    return 
} 
switch t { 
case 1: 
    roomsLen, err := binary.ReadUvarint(buffer) 
    if err != nil { 
     utils.Log("Error while reading rooms len " + err.Error()) 
     return 
    } 
    utils.Log(roomsLen) 
    roomsBytes := make([]byte, roomsLen) 
    binary.Read(buffer, binary.LittleEndian, roomsBytes) 
    rooms := []*Room{} 
    err = json.Unmarshal(roomsBytes, rooms) 
    if err != nil { 
     utils.Log("Error while unmarshaling room list " + err.Error()) 
     return 
    } 
    utils.Log(rooms) 

的utils.Log函數僅是本

func Log(msg interface{}) { 
    n := time.Now() 
    console.Call("log", fmt.Sprintf("[%v:%v:%v] %v", n.Hour(), n.Minute(), n.Second(), msg)) 
} 

事情是第一UINT64是一個IM等待(1),但是在第二UINT64 IM讀數始終爲0,而​​它洛(LEN(消息))給我52

而且由於其始終爲0我不能解組得當

所以我不知道我做錯了,或者這是不是使用WebSockets的正確道路。

回答

1

小錯誤。您正在寫uint64,但使用「ReadUvarint」來讀取它(varint是一種不同類型的數據)。

package main 

import (
    "bytes" 
    "encoding/binary" 
    "fmt" 
) 

func main() { 
    b := bytes.NewBuffer([]byte{}) 
    e1 := binary.Write(b, binary.LittleEndian, uint64(10)) 
    e2 := binary.Write(b, binary.LittleEndian, uint64(20)) 

    fmt.Println("writing 10 and 20", e1, e2) 

    { 
     r := bytes.NewBuffer(b.Bytes()) 
     res, e := binary.ReadUvarint(r) 
     res2, e2 := binary.ReadUvarint(r) 
     fmt.Println("using readuvarint here  :", res, res2, e, e2, b.Bytes()) 
    } 
    { 
     r := bytes.NewBuffer(b.Bytes()) 
     var res, res2 uint64 
     e := binary.Read(r, binary.LittleEndian, &res) 
     e2 := binary.Read(r, binary.LittleEndian, &res2) 
     fmt.Println("using read into uint64's here :", res, res2, e, e2, b.Bytes()) 
    } 
}