golang基于长度解决粘包问题(gnet)

使用gnet框架处理Socket粘包问题

当服务端处理旧业务tcp scoket,旧的业务是Netty Socket使用的是2个字节的长度定义数据的大小。官方支持ICodec去处理,但文档不太友好,这里附上使用方法

import (
	"github.com/panjf2000/gnet"
)

type DTUSocketServer struct {
	*gnet.EventServer
}
var codec gnet.ICodec
//2个字节长度编解码器,使用方法,外部初始化调用
func InitDTUTerminalSocketServer() {
	if codec == nil {
		encoderConfig := gnet.EncoderConfig{
			ByteOrder:                       binary.BigEndian,
			LengthFieldLength:               2,
			LengthAdjustment:                0,
			LengthIncludesLengthFieldLength: false,
		}
		decoderConfig := gnet.DecoderConfig{
			ByteOrder:           binary.BigEndian,
			LengthFieldOffset:   0,
			LengthFieldLength:   2,
			LengthAdjustment:    0,
			InitialBytesToStrip: 2,
		}
		codec = gnet.NewLengthFieldBasedFrameCodec(encoderConfig, decoderConfig)
	}

	addr := fmt.Sprintf("tcp://:%d", 8888)
	Server := new(DTUSocketServer)
    //codec应用
	err := gnet.Serve(Server, addr, gnet.WithMulticore(true), gnet.WithCodec(codec), gnet.WithReusePort(true), gnet.WithTCPKeepAlive(5*time.Second))
	if err != nil {
		//log.Errorf("DTU终端TCP服务启动失败:%s", err)
	}
}

posted @ 2024-03-11 15:56  jomz  阅读(231)  评论(0编辑  收藏  举报