- 主题:求指路:udp发送固定长度sring
收json,发送私有协议udp
udp对应c代码大概是
struct demo{
int abc;
char content[32];
};
struct demo test;
memset(&test, 0, sizeof(test));
test.abc =5;
strcpy(test.content, "my test");
send(fd, &test, sizeof(test));
go里面好像不能指定string的固定长度,我解析json之后,难道只能一个字节一个字节赋值?
--
FROM 106.120.101.*
谢谢了
【 在 flw 的大作中提到: 】
: 你这里的 test.abc = 5 最好改成 test.abc = htons(5),
: 然后 Go 这边你用 encoding/binary 就可以读了,参见:
: $ go doc encoding/binary.Read
: ...................
--
FROM 106.120.101.*
写完了, 感谢指路
部分关键代码
import (
"encoding/binary"
)
buff := bytes.NewBuffer([]byte{})
var abc int32
abc = 7777
err = binary.Write(buff, binary.BigEndian, &abc)
if err != nil {
log.Panic(err)
}
content := "abcdefg"
err = binary.Write(buff, binary.BigEndian, []byte(content))
if err != nil {
log.Panic(err)
}
var zeroByte uint8
/* fixed length 27 bytes */
end := 27 - len(content)
for i := 1; i <= end; i++ {
err = binary.Write(buff, binary.BigEndian, &zeroByte)
if err != nil {
log.Panic(err)
}
}
sendBuff := buff.Bytes()
_, err = socket.Write(sendBuff) // 发送数据
if err != nil {
fmt.Println("发送数据失败,err: ", err)
return
}
【 在 flw 的大作中提到: 】
: 你这里的 test.abc = 5 最好改成 test.abc = htons(5),
: 然后 Go 这边你用 encoding/binary 就可以读了,参见:
: $ go doc encoding/binary.Read
: ...................
--
修改:lioncat7 FROM 106.120.101.*
FROM 106.120.101.*
第一次写go,[]byte(zeroByte)这块说无法转换
var zeroByte uint8
repeateTime := 27 - len(incoming.SrcAddr)
if repeateTime != 0 {
binary.Write(buff, binary.BigEndian, bytes.Repeat([]byte(zeroByte), repeateTime))
}
【 在 flw 的大作中提到: 】
: 27 bytes 那里可以简化一下,
: 直接用 bytes.Repeat 生成个切片发出去就好了,类似于 memset:
: $ go doc bytes.Repeat
: ...................
--
FROM 106.120.101.*
解决了
repeateTime := 27 - len(incoming.SrcAddr)
if repeateTime != 0 {
binary.Write(buff, binary.BigEndian, bytes.Repeat([]byte{0}, repeateTime))
}
另外请问下 我只过了一遍 the go programming language
如果想快速过一下go都提供了哪些基础库 有什么推荐么
【 在 flw 的大作中提到: 】
: 27 bytes 那里可以简化一下,
: 直接用 bytes.Repeat 生成个切片发出去就好了,类似于 memset:
: $ go doc bytes.Repeat
: ...................
--
FROM 106.120.101.*
谢谢
【 在 flw 的大作中提到: 】
: 直接看手册,甚至看源码
: 有几个实用的命令,给你介绍一下。假设你用的是 Go 的较新版本,那么:
: $ GO111MODULE=off GOPATH=$(go env GOROOT) go list all
: ...................
--
FROM 106.120.101.*