[英]Golang: dealing with binary data
I have application client(javascript)-server(golang) and the connection between them are all over websocket. 我有应用程序客户端(javascript)-server(golang),它们之间的连接遍布websocket。 I'm planing using binary messages and i want to create my own protocol for messaging like in this page protocol . 我正在使用二进制消息进行规划,我想在此页面协议中创建自己的消息传递协议 。
I'm already figure it out in javascript by using DataView but not in golang. 我已经通过使用DataView而不是golang在javascript中弄明白了。 Event the primitive data type are similar like they have int8, uint8, int16, uint16 etc, i can't figure it out. 事件原始数据类型类似于他们有int8,uint8,int16,uint16等,我无法弄明白。
This is the message frame: 这是消息帧:
1 Uint8 opcode
2 Uint16 msg
This is the example of javascript code handling the incoming message form websocket with message frame above: 这是javascript代码处理传入消息表单websocket的示例,其中包含上面的消息帧:
websocket.onmessage = function(evt) {
var data = new DataView(evt.data);
var opcode = data.getUint8(0);
var msg = data.getUint16(1);
}
Can you show me how to do it in golang? 你能告诉我怎么在golang做吗? i'm using gorilla websocket . 我正在使用大猩猩websocket 。 I know that read message are in []byte
, but i don't know how to slice it like javascript does with DataView. 我知道读取消息是在[]byte
,但我不知道如何切片,就像javascript与DataView一样。
Thanks 谢谢
For the uint16 you'll need the binary package. 对于uint16,您需要二进制包。 Double-check if LittleEndian is what you want. 仔细检查LittleEndian是否符合您的要求。
package main
import (
"encoding/binary"
)
func main() {
a := []byte("yak")
/* opcode */ _ = uint8(a[0])
/* message */ _ = binary.LittleEndian.Uint16(a[1:3])
}
https://play.golang.org/p/HRu7C5h2a5 https://play.golang.org/p/HRu7C5h2a5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.