1 Star 0 Fork 0

叶明志 / golang练习

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
utils.go 1010 Bytes
一键复制 编辑 原始数据 按行查看 历史
yemingzhi 提交于 2020-03-17 16:27 . 乱写的,没提交
package utils
import (
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"go_code/chatsys/common"
"net"
"time"
)
//这个结构体,完成对服务器端发送和接收消息包的读取
type Transfer struct {
Conn net.Conn
Buf [8192]byte
}
func (tf *Transfer) ClientReadPackage() (msg common.Message, err error) {
//var buf [8192]byte
n, err := tf.Conn.Read(tf.Buf[0:4])
if n != 4 {
err = errors.New("read header failed")
fmt.Println("如果读取错误, 则休息30秒,再读数据...")
time.Sleep(time.Second * 30)
return
}
//fmt.Println("read package:", buf[0:4])
var packLen uint32
packLen = binary.BigEndian.Uint32(tf.Buf[0:4])
//fmt.Printf("receive len:%d", packLen)
n, err = tf.Conn.Read(tf.Buf[0:packLen])
if n != int(packLen) {
err = errors.New("read body failed")
return
}
//fmt.Printf("receive data:%s\n", string(buf[0:packLen]))
err = json.Unmarshal(tf.Buf[0:packLen], &msg)
if err != nil {
fmt.Println("unmarshal failed, err:", err)
}
return
}
Go
1
https://gitee.com/yemingzhi/GolangLearnPractice1.git
git@gitee.com:yemingzhi/GolangLearnPractice1.git
yemingzhi
GolangLearnPractice1
golang练习
2bf136849dce

搜索帮助