Browse Source

rewrite test case

master
Roger 5 years ago
parent
commit
29c4df1237
  1. 2
      znet/connection.go
  2. 6
      znet/datapack.go
  3. 94
      znet/datapack_test.go
  4. 87
      znet/server_test.go

2
znet/connection.go

@ -194,7 +194,7 @@ func (c *Connection) RemoteAddr() net.Addr {
//直接将Message数据发送数据给远程的TCP客户端 //直接将Message数据发送数据给远程的TCP客户端
func (c *Connection) SendMsg(msgId uint32, data []byte) error { func (c *Connection) SendMsg(msgId uint32, data []byte) error {
if c.isClosed == true { if c.isClosed == true {
return errors.New("Connection closed when send msg")
return errors.New("connection closed when send msg")
} }
//将data封包,并且发送 //将data封包,并且发送
dp := NewDataPack() dp := NewDataPack()

6
znet/datapack.go

@ -21,6 +21,7 @@ func(dp *DataPack) GetHeadLen() uint32 {
//Id uint32(4字节) + DataLen uint32(4字节) //Id uint32(4字节) + DataLen uint32(4字节)
return 8 return 8
} }
//封包方法(压缩数据) //封包方法(压缩数据)
func(dp *DataPack) Pack(msg ziface.IMessage)([]byte, error) { func(dp *DataPack) Pack(msg ziface.IMessage)([]byte, error) {
//创建一个存放bytes字节的缓冲 //创建一个存放bytes字节的缓冲
@ -43,6 +44,7 @@ func(dp *DataPack) Pack(msg ziface.IMessage)([]byte, error) {
return dataBuff.Bytes(), nil return dataBuff.Bytes(), nil
} }
//拆包方法(解压数据) //拆包方法(解压数据)
func(dp *DataPack) Unpack(binaryData []byte)(ziface.IMessage, error) { func(dp *DataPack) Unpack(binaryData []byte)(ziface.IMessage, error) {
//创建一个从输入二进制数据的ioReader //创建一个从输入二进制数据的ioReader
@ -62,8 +64,8 @@ func(dp *DataPack) Unpack(binaryData []byte)(ziface.IMessage, error) {
} }
//判断dataLen的长度是否超出我们允许的最大包长度 //判断dataLen的长度是否超出我们允许的最大包长度
if (utils.GlobalObject.MaxPacketSize > 0 && msg.DataLen > utils.GlobalObject.MaxPacketSize) {
return nil, errors.New("Too large msg data recieved")
if utils.GlobalObject.MaxPacketSize > 0 && msg.DataLen > utils.GlobalObject.MaxPacketSize {
return nil, errors.New("too large msg data received")
} }
//这里只需要把head的数据拆包出来就可以了,然后再通过head的长度,再从conn读取一次数据 //这里只需要把head的数据拆包出来就可以了,然后再通过head的长度,再从conn读取一次数据

94
znet/datapack_test.go

@ -5,39 +5,43 @@ import (
"io" "io"
"net" "net"
"testing" "testing"
"time"
) )
// run in terminal:
// go test -v ./znet -run=TestDataPack
//只是负责测试datapack拆包,封包功能 //只是负责测试datapack拆包,封包功能
func TestDataPack(t *testing.T) { func TestDataPack(t *testing.T) {
//创建socket TCP Server //创建socket TCP Server
listener, err := net.Listen("tcp", "127.0.0.1:7777") listener, err := net.Listen("tcp", "127.0.0.1:7777")
if err != nil{
if err != nil {
fmt.Println("server listen err:", err) fmt.Println("server listen err:", err)
return return
} }
//创建服务器gotoutine,负责从客户端goroutine读取粘包的数据,然后进行解析 //创建服务器gotoutine,负责从客户端goroutine读取粘包的数据,然后进行解析
go func (){
for{
go func() {
for {
conn, err := listener.Accept() conn, err := listener.Accept()
if err != nil{
if err != nil {
fmt.Println("server accept err:", err) fmt.Println("server accept err:", err)
} }
//处理客户端请求 //处理客户端请求
go func(conn net.Conn){
go func(conn net.Conn) {
//创建封包拆包对象dp //创建封包拆包对象dp
dp := NewDataPack() dp := NewDataPack()
for{
for {
//1 先读出流中的head部分 //1 先读出流中的head部分
headData := make([]byte, dp.GetHeadLen()) headData := make([]byte, dp.GetHeadLen())
_, err := io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
_, err := io.ReadFull(conn, headData) //ReadFull 会把msg填充满为止
if err != nil { if err != nil {
fmt.Println("read head error") fmt.Println("read head error")
} }
//将headData字节流 拆包到msg中 //将headData字节流 拆包到msg中
msgHead,err := dp.Unpack(headData)
if err != nil{
msgHead, err := dp.Unpack(headData)
if err != nil {
fmt.Println("server unpack err:", err) fmt.Println("server unpack err:", err)
return return
} }
@ -58,50 +62,54 @@ func TestDataPack(t *testing.T) {
} }
} }
}(conn) }(conn)
} }
}() }()
//客户端goroutine,负责模拟粘包的数据,然后进行发送 //客户端goroutine,负责模拟粘包的数据,然后进行发送
conn, err := net.Dial("tcp", "127.0.0.1:7777")
if err != nil{
fmt.Println("client dial err:", err)
return
}
go func() {
conn, err := net.Dial("tcp", "127.0.0.1:7777")
if err != nil {
fmt.Println("client dial err:", err)
return
}
//创建一个封包对象 dp
dp := NewDataPack()
//创建一个封包对象 dp
dp := NewDataPack()
//封装一个msg1包
msg1 := &Message{
Id:0,
DataLen:5,
Data:[]byte{'h', 'e', 'l', 'l', 'o'},
}
//封装一个msg1包
msg1 := &Message{
Id: 0,
DataLen: 5,
Data: []byte{'h', 'e', 'l', 'l', 'o'},
}
sendData1, err := dp.Pack(msg1)
if err!= nil{
fmt.Println("client pack msg1 err:", err)
return
}
sendData1, err := dp.Pack(msg1)
if err != nil {
fmt.Println("client pack msg1 err:", err)
return
}
msg2 := &Message{
Id:1,
DataLen:7,
Data:[]byte{'w', 'o', 'r', 'l', 'd', '!', '!'},
}
sendData2, err := dp.Pack(msg2)
if err!= nil{
fmt.Println("client temp msg2 err:", err)
return
}
msg2 := &Message{
Id: 1,
DataLen: 7,
Data: []byte{'w', 'o', 'r', 'l', 'd', '!', '!'},
}
sendData2, err := dp.Pack(msg2)
if err != nil {
fmt.Println("client temp msg2 err:", err)
return
}
//将sendData1,和 sendData2 拼接一起,组成粘包
sendData1 = append(sendData1, sendData2...)
//将sendData1,和 sendData2 拼接一起,组成粘包
sendData1 = append(sendData1, sendData2...)
//向服务器端写数据
conn.Write(sendData1)
//向服务器端写数据
conn.Write(sendData1)
}()
//客户端阻塞 //客户端阻塞
select{}
select {
case <-time.After(time.Second):
return
}
} }

87
znet/server_test.go

@ -2,12 +2,16 @@ package znet
import ( import (
"fmt" "fmt"
"github.com/aceld/zinx/ziface"
"io"
"net" "net"
"testing" "testing"
"time" "time"
"github.com/aceld/zinx/ziface"
) )
// run in terminal:
// go test -v ./znet -run=TestServer
/* /*
模拟客户端 模拟客户端
*/ */
@ -17,47 +21,57 @@ func ClientTest() {
//3秒之后发起测试请求,给服务端开启服务的机会 //3秒之后发起测试请求,给服务端开启服务的机会
time.Sleep(3 * time.Second) time.Sleep(3 * time.Second)
conn, err := net.Dial("tcp", "127.0.0.1:7777")
conn, err := net.Dial("tcp", "127.0.0.1:8999")
if err != nil { if err != nil {
fmt.Println("client start err, exit!") fmt.Println("client start err, exit!")
return return
} }
for { for {
_, err := conn.Write([]byte("Zinx V0.2 test"))
dp := NewDataPack()
msg, _ := dp.Pack(NewMsgPackage(1, []byte("client test message")))
_, err := conn.Write(msg)
if err != nil { if err != nil {
fmt.Println("write error err ", err)
fmt.Println("client write err: ", err)
return return
} }
buf := make([]byte, 512)
cnt, err := conn.Read(buf)
//先读出流中的head部分
headData := make([]byte, dp.GetHeadLen())
_, err = io.ReadFull(conn, headData)
if err != nil { if err != nil {
fmt.Println("read buf error ")
fmt.Println("client read head err: ", err)
return return
} }
fmt.Printf(" server call back : %s, cnt = %d\n", buf, cnt)
time.Sleep(1 * time.Second)
}
}
/*
//Server 模块的测试函数
func TestServer(t *testing.T) {
// 将headData字节流 拆包到msg中
msgHead, err := dp.Unpack(headData)
if err != nil {
fmt.Println("client unpack head err: ", err)
return
}
if msgHead.GetDataLen() > 0 {
//msg 是有data数据的,需要再次读取data数据
msg := msgHead.(*Message)
msg.Data = make([]byte, msg.GetDataLen())
// 服务端测试
//1 创建一个server 句柄 s
s := NewServer("[zinx V0.1]")
//根据dataLen从io中读取字节流
_, err := io.ReadFull(conn, msg.Data)
if err != nil {
fmt.Println("client unpack data err")
return
}
// 客户端测试
go ClientTest()
fmt.Printf("==> Client receive Msg: Id = %d, len = %d , data = %s\n", msg.Id, msg.DataLen, msg.Data)
}
//2 开启服务
s.Serve()
time.Sleep(time.Second)
}
} }
/*
模拟服务器端
*/ */
//ping test 自定义路由 //ping test 自定义路由
@ -65,43 +79,50 @@ type PingRouter struct {
BaseRouter BaseRouter
} }
//Test PreHandle //Test PreHandle
func (this *PingRouter) PreHandle(request ziface.IRequest) { func (this *PingRouter) PreHandle(request ziface.IRequest) {
fmt.Println("Call Router PreHandle") fmt.Println("Call Router PreHandle")
_, err := request.GetConnection().GetTCPConnection().Write([]byte("before ping ....\n"))
err := request.GetConnection().SendMsg(1, []byte("before ping ....\n"))
if err != nil { if err != nil {
fmt.Println("call back ping ping ping error")
fmt.Println("preHandle SendMsg err: ", err)
} }
} }
//Test Handle //Test Handle
func (this *PingRouter) Handle(request ziface.IRequest) { func (this *PingRouter) Handle(request ziface.IRequest) {
fmt.Println("Call PingRouter Handle") fmt.Println("Call PingRouter Handle")
_, err := request.GetConnection().GetTCPConnection().Write([]byte("ping...ping...ping\n"))
//先读取客户端的数据,再回写ping...ping...ping
fmt.Println("recv from client : msgId=", request.GetMsgID(), ", data=", string(request.GetData()))
err := request.GetConnection().SendMsg(1, []byte("ping...ping...ping\n"))
if err != nil { if err != nil {
fmt.Println("call back ping ping ping error")
fmt.Println("Handle SendMsg err: ", err)
} }
} }
//Test PostHandle //Test PostHandle
func (this *PingRouter) PostHandle(request ziface.IRequest) { func (this *PingRouter) PostHandle(request ziface.IRequest) {
fmt.Println("Call Router PostHandle") fmt.Println("Call Router PostHandle")
_, err := request.GetConnection().GetTCPConnection().Write([]byte("After ping .....\n"))
err := request.GetConnection().SendMsg(1, []byte("After ping .....\n"))
if err != nil { if err != nil {
fmt.Println("call back ping ping ping error")
fmt.Println("Post SendMsg err: ", err)
} }
} }
func TestServerV0_3(t *testing.T) {
func TestServer(t *testing.T) {
//创建一个server句柄 //创建一个server句柄
s := NewServer() s := NewServer()
s.AddRouter(&PingRouter{})
s.AddRouter(1, &PingRouter{})
// 客户端测试 // 客户端测试
go ClientTest() go ClientTest()
//2 开启服务 //2 开启服务
s.Serve()
go s.Serve()
select {
case <-time.After(time.Second * 10):
return
}
} }
Loading…
Cancel
Save