tcptemplate/test/cli_test.go

116 lines
2.3 KiB
Go

package test
import (
"bytes"
"encoding/binary"
_ "github.com/golang/protobuf/proto"
_ "github.com/hprose/hprose-golang/io"
_ "github.com/trysh/ttb"
_ "go-tcpFramework-rudy/protocol/pb"
_ "io"
"log"
"net"
_ "net/http/pprof"
_ "runtime"
"testing"
"time"
)
/*
tcp 测试程序,测试以下场景
1. 粘包场景,一个数据包分成两次发送
2. 突然断线,客户端长时间
3. 故意捣乱
*/
type PackHeader struct {
Identify [2]byte
Length int32
Verify byte
}
var rBuf []byte
func init() {
rBuf = make([]byte, 1024)
}
func SendPackage(writer *net.TCPConn, payload []byte, length int) error {
var header PackHeader
header.Identify[0] = 0x40
header.Identify[1] = 0x41
header.Length = 4
packbuf := bytes.Buffer{}
buf := bytes.NewBuffer([]byte{})
e := binary.Write(buf, binary.BigEndian, header.Length)
if e != nil {
log.Println(e.Error())
}
for _, v := range buf.Bytes() {
header.Verify += v
}
err := binary.Write(&packbuf, binary.BigEndian, header.Identify)
err = binary.Write(&packbuf, binary.BigEndian, header.Length)
err = binary.Write(&packbuf, binary.BigEndian, header.Verify)
if err != nil {
log.Println(err.Error())
}
b := []byte{}
//log.Println("Send length",wb)
b = append(b, packbuf.Bytes()...)
b = append(b, payload[0:length]...)
log.Println(b[0:5],b[5:])
_, e = writer.Write(b[0:5])
if e != nil {
log.Println(e.Error())
return e
}
_, e = writer.Write(b[5:])
if e != nil {
log.Println(e.Error())
return e
}
return nil
}
func TestCli(t *testing.T) {
for i := 0; i < 1; i++ {
go func() {
seq := int32(0)
payload := bytes.NewBuffer([]byte{})
server := "127.0.0.1:9850"
servAddr, err := net.ResolveTCPAddr("tcp", server)
if err != nil {
log.Println(err.Error())
}
conn, err := net.DialTCP("tcp", nil, servAddr)
if err != nil {
log.Println(err.Error())
return
}
for {
seq++
payload.Reset()
binary.Write(payload, binary.BigEndian, seq)
log.Println("start send", seq)
e := SendPackage(conn, payload.Bytes(), payload.Len())
//n ,e := conn.Write([]byte{'1','2','3','4'})
if e != nil {
log.Println("client exit")
log.Println(e)
return
}
time.Sleep(time.Second)
}
log.Println("client exit")
}()
}
for {
time.Sleep(time.Millisecond * 100)
}
}