This commit is contained in:
2025-06-20 17:00:56 +08:00
parent e17648cb60
commit 1b55403cd6
13 changed files with 1266 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
package codec
import (
"log"
"github.com/panjf2000/gnet/v2"
)
// CROSS_DOMAIN 定义跨域策略文件内容
const CROSS_DOMAIN = "<?xml version=\"1.0\"?><!DOCTYPE cross-domain-policy><cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\" /></cross-domain-policy>\x00"
// TEXT 定义跨域请求的文本格式
const TEXT = "<policy-file-request/>\x00"
// Handle 处理网络连接
func Handle(conn gnet.Conn) error {
// 读取数据并检查是否为跨域请求
data, err := conn.Peek(len(TEXT))
if err != nil {
log.Printf("Error reading cross-domain request: %v", err)
return err
}
if string(data) == TEXT { //判断是否是跨域请求
log.Printf("Received cross-domain request from %s", conn.RemoteAddr())
// 处理跨域请求
conn.Write([]byte(CROSS_DOMAIN))
conn.Discard(len(TEXT))
return nil
}
return nil
}

View File

@@ -0,0 +1,13 @@
package codec
import "github.com/panjf2000/gnet/v2"
type SocketCodec interface {
Encode([]byte) ([]byte, error)
Decode(gnet.Conn) ([]byte, error)
}

View File

@@ -0,0 +1,75 @@
package codec
import (
"encoding/binary"
"errors"
"io"
"github.com/panjf2000/gnet/v2"
)
var ErrIncompletePacket = errors.New("incomplete packet")
// TomeeSocketCodec 协议格式:
//
// * 0 4
// * +-----------+
// * | body len |
// * +-----------+
// * | |
// * + +
// * | body bytes|
// * + +
// * | ... ... |
// * +-----------+
type TomeeSocketCodec struct{}
var _ SocketCodec = (*TomeeSocketCodec)(nil)
func NewTomeeSocketCodec() *TomeeSocketCodec {
return &TomeeSocketCodec{}
}
func (codec TomeeSocketCodec) Encode(buf []byte) ([]byte, error) {
bodyLen := len(buf)
data := make([]byte, 4+bodyLen)
// 写入4字节的包长度
binary.BigEndian.PutUint32(data[:4], uint32(bodyLen))
// 写入包体
copy(data[4:], buf)
return data, nil
}
func (codec TomeeSocketCodec) Decode(c gnet.Conn) ([]byte, error) {
// 先读取4字节的包长度
lenBuf, err := c.Peek(4)
if err != nil {
if errors.Is(err, io.ErrShortBuffer) {
return nil, ErrIncompletePacket
}
return nil, err
}
bodyLen := binary.BigEndian.Uint32(lenBuf)
totalLen := 4 + int(bodyLen)
// 检查整个包是否完整
buf, err := c.Peek(totalLen)
if err != nil {
if errors.Is(err, io.ErrShortBuffer) {
return nil, ErrIncompletePacket
}
return nil, err
}
// 提取包体
body := make([]byte, bodyLen)
copy(body, buf[4:totalLen])
// 从缓冲区中丢弃已读取的数据
_, _ = c.Discard(totalLen)
return body, nil
}