bootstrap
.group(group)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
socketChannel.pipeline()
.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, 1024, 0, 4, 0, 0, true))
.addLast(new LengthFieldPrepender(ByteOrder.LITTLE_ENDIAN, 4, 0, false))
.addLast(new ClientHandler());
}
});
我在netty client 这边加了个编码以及字节发送循序
而go这边加了一个解码,我这边是自定义私有协议,固定的头,每条消息包含一个头6个字节
func decode(reader *bufio.Reader) (string, error) {
// 读取消息的长度
lengthByte, _ := reader.Peek(6) // 读取前6个字节的数据
lengthBuff := bytes.NewBuffer(lengthByte)
var length int32
err := binary.Read(lengthBuff, binary.LittleEndian, &length)
if err != nil {
return "", err
}
// Buffered返回缓冲中现有的可读取的字节数。
if int32(reader.Buffered()) < length+6 {
return "", err
}
//读取消息体
pack := make([]byte, int(6+length))
_, err = reader.Read(pack)
if err != nil {
return "", err
}
fmt.Printf("消息版本:%d\n", int8(pack[1]))
fmt.Printf("消息类型:%d\n", int8(pack[0]>>2))
return string(pack[6:]), nil
}
func byte2Int(b1, b2 byte) int {
var v int
v = int((b2 & 0xFF) | (b1&0xFF)<<8)
return v
}
func main() {
gtcp.NewServer("127.0.0.1:30000", func(conn *gtcp.Conn) {
defer conn.Close()
reader := bufio.NewReader(conn)
for {
msg, err := decode(reader)
if err == io.EOF {
break
}
if err != nil {
fmt.Println("decode msg failed!! err:", err)
break
}
fmt.Printf("收到客户端消息:%v\n", msg)
}
}).Run()
}
现在go这边能收到消息,但是会出一死循环,估计解码不正确,不能break掉