验证中...
片段 1 片段 2 片段 3
protocol.go
原始数据 复制代码
package protocol
import (
"bytes"
"encoding/binary"
)
const (
ConstHeader = 0xff91 //2 byte magic
)
//封包
func Packet(message []byte) []byte {
size := len(message)
buff := make([]byte, 0)
buff = append(buff, IntToBytes(ConstHeader)...) //magic
buff = append(buff, IntToBytes(size)...) //length
buff = append(buff, message...) //content
return buff
}
//解包
func Unpack(buffer []byte) ([]byte, bool) {
length := len(buffer)
if length < 6 {
//小于预定长度则直接返回原数组
return buffer, false
}
if BytesToInt(buffer[0:4]) == int(ConstHeader) {
//解析数据长度
messageLength := BytesToInt(buffer[4:8])
//长度太小则直接返回
if length < 8+messageLength {
return buffer, false
}
//readerChannel <- buffer[4:messageLength]
return buffer[8 : 8+messageLength], true
} else {
return buffer, false
}
}
//整形转换成字节
func IntToBytes(n int) []byte {
x := int32(n)
bytesBuffer := bytes.NewBuffer([]byte{})
binary.Write(bytesBuffer, binary.BigEndian, x)
return bytesBuffer.Bytes()
}
//字节转换成整形
func BytesToInt(b []byte) int {
bytesBuffer := bytes.NewBuffer(b)
var x int32
binary.Read(bytesBuffer, binary.BigEndian, &x)
return int(x)
}
server.go
原始数据 复制代码
package main
import (
"./protocol"
"fmt"
"net"
"strconv"
)
func main() {
l, err := net.Listen("tcp4", "0.0.0.0:8090")
if err != nil {
fmt.Println(err.Error())
}
defer l.Close()
for {
conn, err := l.Accept()
if err != nil {
fmt.Println(err.Error())
break
}
go loop(conn)
}
}
func loop(conn net.Conn) {
go broadCast(conn)
buf := make([]byte, 2048)
tmpBuffer := make([]byte, 0) //临时缓冲区
for {
length, err := conn.Read(buf)
if err != nil {
fmt.Println(err.Error())
break
}
//message := string(buf[0:length])
remain, ready := protocol.Unpack(buf[0:length])
if ready {
fmt.Println("rec:", string(remain[0:length]))
tmpBuffer = tmpBuffer[0:0:0]
} else {
tmpBuffer = append(tmpBuffer, remain...)
}
}
}
//模拟广播消息
func broadCast(conn net.Conn) {
i := 0
for {
conn.Write(protocol.Packet([]byte("hello world|" + strconv.Itoa(i))))
i++
}
}
client.go
原始数据 复制代码
package main
import (
"./protocol"
"fmt"
"net"
)
func main() {
addr, err := net.ResolveTCPAddr("tcp4", "0.0.0.0:8090")
if err != nil {
fmt.Println(err.Error())
}
tcpCon, err := net.DialTCP("tcp4", nil, addr)
if err != nil {
fmt.Println(err.Error())
return
}
if tcpCon == nil {
panic("链接失败..")
}
go clientLoop(tcpCon)
for {
var input string
fmt.Scanln(&input)
if len(input) > 0 {
tcpCon.Write(protocol.Packet([]byte(input)))
}
}
}
func clientLoop(conn *net.TCPConn) {
buff := make([]byte, 2048)
tmpBuffer := make([]byte, 0) //临时缓冲区
for {
length, err := conn.Read(buff)
if err != nil {
fmt.Println(err.Error())
break
}
//message := string(buf[0:length])
remain, ready := protocol.Unpack(buff[0:length])
if ready {
fmt.Println("client rec:", string(remain[0:]))
tmpBuffer = tmpBuffer[0:0:0]
} else {
tmpBuffer = append(tmpBuffer, remain...)
}
}
}

评论列表( 0 )

你可以在登录后,发表评论

搜索帮助