当前位置: 移动技术网 > IT编程>脚本编程>Go语言 > GO语言如何手动处理TCP粘包详解

GO语言如何手动处理TCP粘包详解

2018年01月25日  | 移动技术网IT编程  | 我要评论

前言

一般所谓的tcp粘包是在一次接收数据不能完全地体现一个完整的消息数据。tcp通讯为何存在粘包呢?主要原因是tcp是以流的方式来处理数据,再加上网络上mtu的往往小于在应用处理的消息数据,所以就会引发一次接收的数据无法满足消息的需要,导致粘包的存在。处理粘包的唯一方法就是制定应用层的数据通讯协议,通过协议来规范现有接收的数据是否满足消息数据的需要。在应用中处理粘包的基础方法主要有两种分别是以4节字描述消息大小或以结束符,实际上也有两者相结合的如http,redis的通讯协议等。

应用场景

大部分tcp通讯场景下,使用自定义通讯协议

粘包处理原理:通过请求头中数据包大小,将客户端n次发送的数据缓冲到一个数据包中

例如:

请求头占3个字节(指令头1字节、数据包长度2字节),版本占1个字节,指令占2个字节

协议规定一个数据包最大是512字节,请求头中数据包记录是1300字节,完整的数据包是1307个字节,此时服务器端需要将客户端3次发送数据进行粘包处理

代码示例

package server
import (
 "net"
 "bufio"
 "ftj-data-synchro/protocol"
 "golang.org/x/text/transform"
 "golang.org/x/text/encoding/simplifiedchinese"
 "io/ioutil"
 "bytes"
 "ftj-data-synchro/logic"
 "fmt"
 "strconv"
)
/*
 客户端结构体
 */
type client struct {
 deviceid string  //客户端连接的唯标志
 conn  net.conn  //连接
 reader *bufio.reader //读取
 writer *bufio.writer //输出
 data  []byte  //接收数据
}
func newclient(conn *net.tcpconn) *client {
 reader := bufio.newreadersize(conn, 10240)
 writer := bufio.newwriter(conn)
 c := &client{conn:conn, reader:reader, writer:writer}
 return c
}
/**
 数据读取(粘包处理)
 */
func (this *client)read() {
 for {
  var data []byte
  var err error
  //读取指令头 返回输入流的前4个字节,不会移动读取位置
  data, err = this.reader.peek(4)
  if len(data) == 0 || err != nil {
   continue
  }
  //返回缓冲中现有的可读取的字节数
  var bytesize = this.reader.buffered()
  fmt.printf("读取字节长度:%d\n", bytesize)
  //生成一个字节数组,大小为缓冲中可读字节数
  data = make([]byte, bytesize)
  //读取缓冲中的数据
  this.reader.read(data)
  fmt.printf("读取字节:%d\n", data)
  //保存到新的缓冲区
  for _, v := range data {
   this.data = append(this.data, v)
  }
  if len(this.data) < 4 {
   //数据包缓冲区清空
   this.data = []byte{}
   fmt.printf("非法数据,无指令头...\n")
   continue
  }
  data, err = protocol.hexbytestobytes(this.data[:4])
  instructhead, _ := strconv.parseuint(string(data), 16, 16)
  //指令头效验
  if uint16(instructhead) != 42330 {
   fmt.printf("非法数据\n")
   //数据包缓冲区清空
   this.data = []byte{}
   continue
  }
  data = this.data[:protocol.header_size]
  var p = protocol.decode(data)
  fmt.printf("消息体长度:%d\n", p.len)
  var bodylength = len(this.data)  
  /**
   判断数据包缓冲区的大小是否小于协议请求头中数据包大小
   如果小于,等待读取下一个客户端数据包,否则对数据包解码进行业务逻辑处理
   */
  if int(p.len) > len(this.data) - protocol.header_size {
   fmt.printf("body体长度:%d,读取的body体长度:%d\n", p.len, bodylength)
   continue
  }
  fmt.printf("实际处理字节:%v\n", this.data)
  p = protocol.decode(this.data)
  //逻辑处理
  go this.logichandler(p)
  //数据包缓冲区清空
  this.data = []byte{}
 }
}

待优化部分:

type client struct {
 deviceid string  //客户端连接的唯标志
 conn  net.conn  //连接
 reader *bufio.reader //读取
 writer *bufio.writer //输出
 data  []byte  //接收数据
}

结构体中data属性可考虑使用bytes.buffer实现。

golang标准库文档:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网