1
This commit is contained in:
514
common/bytearray/bytearray.go
Normal file
514
common/bytearray/bytearray.go
Normal file
@@ -0,0 +1,514 @@
|
||||
package bytearray
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"io"
|
||||
"math"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// ByteArray 提供字节数组的读写操作,支持大小端字节序
|
||||
type ByteArray struct {
|
||||
buf []byte
|
||||
posWrite int
|
||||
posRead int
|
||||
endian binary.ByteOrder
|
||||
}
|
||||
|
||||
// 默认使用大端字节序
|
||||
var defaultEndian binary.ByteOrder = binary.BigEndian
|
||||
|
||||
// bufferpool 用于重用ByteArray实例
|
||||
var bufferpool = &sync.Pool{
|
||||
New: func() interface{} {
|
||||
return &ByteArray{endian: defaultEndian}
|
||||
},
|
||||
}
|
||||
|
||||
// CreateByteArray 创建一个新的ByteArray实例,使用指定的字节数组
|
||||
func CreateByteArray(bytes []byte) *ByteArray {
|
||||
ba := bufferpool.Get().(*ByteArray)
|
||||
ba.buf = bytes
|
||||
ba.ResetPos()
|
||||
return ba
|
||||
}
|
||||
|
||||
// ReleaseByteArray 将ByteArray实例放回池中以便重用
|
||||
func ReleaseByteArray(ba *ByteArray) {
|
||||
ba.Reset()
|
||||
bufferpool.Put(ba)
|
||||
}
|
||||
|
||||
// Length 返回字节数组的总长度
|
||||
func (ba *ByteArray) Length() int {
|
||||
return len(ba.buf)
|
||||
}
|
||||
|
||||
// Available 返回可读取的字节数
|
||||
func (ba *ByteArray) Available() int {
|
||||
return ba.Length() - ba.posRead
|
||||
}
|
||||
|
||||
// SetEndian 设置字节序(大端或小端)
|
||||
func (ba *ByteArray) SetEndian(endian binary.ByteOrder) {
|
||||
ba.endian = endian
|
||||
}
|
||||
|
||||
// GetEndian 获取当前字节序
|
||||
func (ba *ByteArray) GetEndian() binary.ByteOrder {
|
||||
if ba.endian == nil {
|
||||
return defaultEndian
|
||||
}
|
||||
return ba.endian
|
||||
}
|
||||
|
||||
// Grow 确保缓冲区有足够的空间
|
||||
func (ba *ByteArray) Grow(size int) {
|
||||
if size <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
required := ba.posWrite + size
|
||||
if len(ba.buf) >= required {
|
||||
return
|
||||
}
|
||||
|
||||
newBuf := make([]byte, required)
|
||||
copy(newBuf, ba.buf)
|
||||
ba.buf = newBuf
|
||||
}
|
||||
|
||||
// SetWritePos 设置写指针位置
|
||||
func (ba *ByteArray) SetWritePos(pos int) error {
|
||||
if pos < 0 || pos > ba.Length() {
|
||||
return io.EOF
|
||||
}
|
||||
ba.posWrite = pos
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetWriteEnd 将写指针设置到末尾
|
||||
func (ba *ByteArray) SetWriteEnd() {
|
||||
ba.posWrite = ba.Length()
|
||||
}
|
||||
|
||||
// GetWritePos 获取写指针位置
|
||||
func (ba *ByteArray) GetWritePos() int {
|
||||
return ba.posWrite
|
||||
}
|
||||
|
||||
// SetReadPos 设置读指针位置
|
||||
func (ba *ByteArray) SetReadPos(pos int) error {
|
||||
if pos < 0 || pos > ba.Length() {
|
||||
return io.EOF
|
||||
}
|
||||
ba.posRead = pos
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetReadEnd 将读指针设置到末尾
|
||||
func (ba *ByteArray) SetReadEnd() {
|
||||
ba.posRead = ba.Length()
|
||||
}
|
||||
|
||||
// GetReadPos 获取读指针位置
|
||||
func (ba *ByteArray) GetReadPos() int {
|
||||
return ba.posRead
|
||||
}
|
||||
|
||||
// ResetPos 重置读写指针到开始位置
|
||||
func (ba *ByteArray) ResetPos() {
|
||||
ba.posWrite = 0
|
||||
ba.posRead = 0
|
||||
}
|
||||
|
||||
// Reset 重置ByteArray,清空缓冲区并重置指针
|
||||
func (ba *ByteArray) Reset() {
|
||||
ba.buf = nil
|
||||
ba.ResetPos()
|
||||
}
|
||||
|
||||
// Bytes 返回完整的字节数组
|
||||
func (ba *ByteArray) Bytes() []byte {
|
||||
return ba.buf
|
||||
}
|
||||
|
||||
// BytesAvailable 返回从当前读指针位置到末尾的字节数组
|
||||
func (ba *ByteArray) BytesAvailable() []byte {
|
||||
return ba.buf[ba.posRead:]
|
||||
}
|
||||
|
||||
// ========== 写入方法 ==========
|
||||
|
||||
// Write 写入字节数组
|
||||
func (ba *ByteArray) Write(bytes []byte) (int, error) {
|
||||
if len(bytes) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
ba.Grow(len(bytes))
|
||||
n := copy(ba.buf[ba.posWrite:], bytes)
|
||||
ba.posWrite += n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// WriteByte 写入单个字节
|
||||
func (ba *ByteArray) WriteByte(b byte) error {
|
||||
ba.Grow(1)
|
||||
ba.buf[ba.posWrite] = b
|
||||
ba.posWrite++
|
||||
return nil
|
||||
}
|
||||
|
||||
// WriteInt8 写入int8
|
||||
func (ba *ByteArray) WriteInt8(value int8) error {
|
||||
return ba.WriteByte(byte(value))
|
||||
}
|
||||
|
||||
// WriteInt16 写入int16,根据当前字节序处理
|
||||
func (ba *ByteArray) WriteInt16(value int16) error {
|
||||
return ba.writeNumber(value)
|
||||
}
|
||||
|
||||
// WriteUInt16 写入uint16,根据当前字节序处理
|
||||
func (ba *ByteArray) WriteUInt16(value uint16) error {
|
||||
return ba.writeNumber(value)
|
||||
}
|
||||
|
||||
// WriteInt32 写入int32,根据当前字节序处理
|
||||
func (ba *ByteArray) WriteInt32(value int32) error {
|
||||
return ba.writeNumber(value)
|
||||
}
|
||||
|
||||
// WriteUInt32 写入uint32,根据当前字节序处理
|
||||
func (ba *ByteArray) WriteUInt32(value uint32) error {
|
||||
return ba.writeNumber(value)
|
||||
}
|
||||
|
||||
// WriteInt64 写入int64,根据当前字节序处理
|
||||
func (ba *ByteArray) WriteInt64(value int64) error {
|
||||
return ba.writeNumber(value)
|
||||
}
|
||||
|
||||
// WriteUInt64 写入uint64,根据当前字节序处理
|
||||
func (ba *ByteArray) WriteUInt64(value uint64) error {
|
||||
return ba.writeNumber(value)
|
||||
}
|
||||
|
||||
// WriteFloat32 写入float32,根据当前字节序处理
|
||||
func (ba *ByteArray) WriteFloat32(value float32) error {
|
||||
return ba.writeNumber(math.Float32bits(value))
|
||||
}
|
||||
|
||||
// WriteFloat64 写入float64,根据当前字节序处理
|
||||
func (ba *ByteArray) WriteFloat64(value float64) error {
|
||||
return ba.writeNumber(math.Float64bits(value))
|
||||
}
|
||||
|
||||
// WriteBool 写入布尔值
|
||||
func (ba *ByteArray) WriteBool(value bool) error {
|
||||
var b byte
|
||||
if value {
|
||||
b = 1
|
||||
} else {
|
||||
b = 0
|
||||
}
|
||||
return ba.WriteByte(b)
|
||||
}
|
||||
|
||||
// WriteString 写入字符串
|
||||
func (ba *ByteArray) WriteString(value string) error {
|
||||
_, err := ba.Write([]byte(value))
|
||||
return err
|
||||
}
|
||||
|
||||
// WriteUTF 写入UTF字符串(带长度前缀)
|
||||
func (ba *ByteArray) WriteUTF(value string) error {
|
||||
bytes := []byte(value)
|
||||
if err := ba.WriteUInt16(uint16(len(bytes))); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err := ba.Write(bytes)
|
||||
return err
|
||||
}
|
||||
|
||||
// ReadUTF8Array 读取 UTF8 字符串数组(格式:先读取 Int32 长度,再读取多个 UTF 字符串)
|
||||
func (ba *ByteArray) ReadUTF8Array() ([]string, error) {
|
||||
count, err := ba.ReadInt32()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count < 0 {
|
||||
return nil, errors.New("invalid array length")
|
||||
}
|
||||
|
||||
array := make([]string, 0, count)
|
||||
for i := 0; i < int(count); i++ {
|
||||
str, err := ba.ReadUTF()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
array = append(array, str)
|
||||
}
|
||||
return array, nil
|
||||
}
|
||||
|
||||
// ReadInt32Array 读取 Int32 数组(格式:先读取 Int32 长度,再读取多个 Int32)
|
||||
func (ba *ByteArray) ReadInt32Array() ([]int32, error) {
|
||||
count, err := ba.ReadInt32()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if count < 0 {
|
||||
return nil, errors.New("invalid array length")
|
||||
}
|
||||
|
||||
array := make([]int32, 0, count)
|
||||
for i := 0; i < int(count); i++ {
|
||||
val, err := ba.ReadInt32()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
array = append(array, val)
|
||||
}
|
||||
return array, nil
|
||||
}
|
||||
|
||||
// WriteUTF8 写入UTF8字符串(不带长度前缀)
|
||||
func (ba *ByteArray) WriteUTF8(value string) error {
|
||||
_, err := ba.Write([]byte(value))
|
||||
return err
|
||||
}
|
||||
|
||||
// 通用写入数值方法
|
||||
func (ba *ByteArray) writeNumber(value interface{}) error {
|
||||
var size int
|
||||
switch value.(type) {
|
||||
case int8, uint8:
|
||||
size = 1
|
||||
case int16, uint16:
|
||||
size = 2
|
||||
case int32, uint32, float32:
|
||||
size = 4
|
||||
case int64, uint64, float64:
|
||||
size = 8
|
||||
default:
|
||||
return errors.New("unsupported number type")
|
||||
}
|
||||
|
||||
ba.Grow(size)
|
||||
|
||||
switch v := value.(type) {
|
||||
case int8:
|
||||
ba.buf[ba.posWrite] = byte(v)
|
||||
case uint8:
|
||||
ba.buf[ba.posWrite] = v
|
||||
case int16:
|
||||
ba.endian.PutUint16(ba.buf[ba.posWrite:], uint16(v))
|
||||
case uint16:
|
||||
ba.endian.PutUint16(ba.buf[ba.posWrite:], v)
|
||||
case int32:
|
||||
ba.endian.PutUint32(ba.buf[ba.posWrite:], uint32(v))
|
||||
case uint32:
|
||||
ba.endian.PutUint32(ba.buf[ba.posWrite:], v)
|
||||
case int64:
|
||||
ba.endian.PutUint64(ba.buf[ba.posWrite:], uint64(v))
|
||||
case uint64:
|
||||
ba.endian.PutUint64(ba.buf[ba.posWrite:], v)
|
||||
case float32:
|
||||
ba.endian.PutUint32(ba.buf[ba.posWrite:], math.Float32bits(v))
|
||||
case float64:
|
||||
ba.endian.PutUint64(ba.buf[ba.posWrite:], math.Float64bits(v))
|
||||
}
|
||||
|
||||
ba.posWrite += size
|
||||
return nil
|
||||
}
|
||||
|
||||
// ========== 读取方法 ==========
|
||||
|
||||
// Read 读取字节数组到指定缓冲区
|
||||
func (ba *ByteArray) Read(bytes []byte) (int, error) {
|
||||
if len(bytes) == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
if ba.posRead+len(bytes) > ba.Length() {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
n := copy(bytes, ba.buf[ba.posRead:])
|
||||
ba.posRead += n
|
||||
return n, nil
|
||||
}
|
||||
|
||||
// ReadByte 读取单个字节
|
||||
func (ba *ByteArray) ReadByte() (byte, error) {
|
||||
if ba.posRead >= ba.Length() {
|
||||
return 0, io.EOF
|
||||
}
|
||||
|
||||
b := ba.buf[ba.posRead]
|
||||
ba.posRead++
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// ReadInt8 读取int8
|
||||
func (ba *ByteArray) ReadInt8() (int8, error) {
|
||||
b, err := ba.ReadByte()
|
||||
return int8(b), err
|
||||
}
|
||||
|
||||
// ReadUInt8 读取uint8
|
||||
func (ba *ByteArray) ReadUInt8() (uint8, error) {
|
||||
return ba.ReadByte()
|
||||
}
|
||||
|
||||
// ReadInt16 读取int16,根据当前字节序处理
|
||||
func (ba *ByteArray) ReadInt16() (int16, error) {
|
||||
var v uint16
|
||||
if err := ba.readNumber(&v); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int16(v), nil
|
||||
}
|
||||
|
||||
// ReadUInt16 读取uint16,根据当前字节序处理
|
||||
func (ba *ByteArray) ReadUInt16() (uint16, error) {
|
||||
var v uint16
|
||||
if err := ba.readNumber(&v); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// ReadInt32 读取int32,根据当前字节序处理
|
||||
func (ba *ByteArray) ReadInt32() (int32, error) {
|
||||
var v uint32
|
||||
if err := ba.readNumber(&v); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int32(v), nil
|
||||
}
|
||||
|
||||
// ReadUInt32 读取uint32,根据当前字节序处理
|
||||
func (ba *ByteArray) ReadUInt32() (uint32, error) {
|
||||
var v uint32
|
||||
if err := ba.readNumber(&v); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// ReadInt64 读取int64,根据当前字节序处理
|
||||
func (ba *ByteArray) ReadInt64() (int64, error) {
|
||||
var v uint64
|
||||
if err := ba.readNumber(&v); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return int64(v), nil
|
||||
}
|
||||
|
||||
// ReadUInt64 读取uint64,根据当前字节序处理
|
||||
func (ba *ByteArray) ReadUInt64() (uint64, error) {
|
||||
var v uint64
|
||||
if err := ba.readNumber(&v); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// ReadFloat32 读取float32,根据当前字节序处理
|
||||
func (ba *ByteArray) ReadFloat32() (float32, error) {
|
||||
var v uint32
|
||||
if err := ba.readNumber(&v); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return math.Float32frombits(v), nil
|
||||
}
|
||||
|
||||
// ReadFloat64 读取float64,根据当前字节序处理
|
||||
func (ba *ByteArray) ReadFloat64() (float64, error) {
|
||||
var v uint64
|
||||
if err := ba.readNumber(&v); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return math.Float64frombits(v), nil
|
||||
}
|
||||
|
||||
// ReadBool 读取布尔值
|
||||
func (ba *ByteArray) ReadBool() (bool, error) {
|
||||
b, err := ba.ReadByte()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return b != 0, nil
|
||||
}
|
||||
|
||||
// ReadString 读取指定长度的字符串
|
||||
func (ba *ByteArray) ReadString(length int) (string, error) {
|
||||
if length < 0 {
|
||||
return "", errors.New("invalid string length")
|
||||
}
|
||||
|
||||
if ba.posRead+length > ba.Length() {
|
||||
return "", io.EOF
|
||||
}
|
||||
|
||||
str := string(ba.buf[ba.posRead : ba.posRead+length])
|
||||
ba.posRead += length
|
||||
return str, nil
|
||||
}
|
||||
|
||||
// ReadUTF 读取UTF字符串(带长度前缀)
|
||||
func (ba *ByteArray) ReadUTF() (string, error) {
|
||||
length, err := ba.ReadUInt16()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return ba.ReadString(int(length))
|
||||
}
|
||||
|
||||
// 通用读取数值方法
|
||||
func (ba *ByteArray) readNumber(value interface{}) error {
|
||||
var size int
|
||||
switch value.(type) {
|
||||
case *int16, *uint16:
|
||||
size = 2
|
||||
case *int32, *uint32, *float32:
|
||||
size = 4
|
||||
case *int64, *uint64, *float64:
|
||||
size = 8
|
||||
default:
|
||||
return errors.New("unsupported number type")
|
||||
}
|
||||
|
||||
if ba.posRead+size > ba.Length() {
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
buf := ba.buf[ba.posRead : ba.posRead+size]
|
||||
ba.posRead += size
|
||||
|
||||
switch v := value.(type) {
|
||||
case *int16:
|
||||
*v = int16(ba.endian.Uint16(buf))
|
||||
case *uint16:
|
||||
*v = ba.endian.Uint16(buf)
|
||||
case *int32:
|
||||
*v = int32(ba.endian.Uint32(buf))
|
||||
case *uint32:
|
||||
*v = ba.endian.Uint32(buf)
|
||||
case *int64:
|
||||
*v = int64(ba.endian.Uint64(buf))
|
||||
case *uint64:
|
||||
*v = ba.endian.Uint64(buf)
|
||||
case *float32:
|
||||
*v = math.Float32frombits(ba.endian.Uint32(buf))
|
||||
case *float64:
|
||||
*v = math.Float64frombits(ba.endian.Uint64(buf))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
360
common/player/Server.go
Normal file
360
common/player/Server.go
Normal file
@@ -0,0 +1,360 @@
|
||||
package socket
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
)
|
||||
|
||||
// Server 游戏服务器核心类,管理玩家、星球和游戏逻辑
|
||||
type Server struct {
|
||||
players map[int64]*entity.Player
|
||||
planets map[int64]*planet.Planet
|
||||
mutex sync.RWMutex
|
||||
gameRepo repo.GameResourceRepo
|
||||
serverRepo repo.ServerRepo
|
||||
accountRepo repo.AccountRepo
|
||||
playerInfoRepo repo.PlayerInfoRepo
|
||||
playerItemRepo repo.PlayerItemInfoRepo
|
||||
petRepo repo.PetRepo
|
||||
}
|
||||
|
||||
// NewServer 创建新的游戏服务器实例
|
||||
func NewServer(
|
||||
gameRepo repo.GameResourceRepo,
|
||||
serverRepo repo.ServerRepo,
|
||||
accountRepo repo.AccountRepo,
|
||||
playerInfoRepo repo.PlayerInfoRepo,
|
||||
playerItemRepo repo.PlayerItemInfoRepo,
|
||||
petRepo repo.PetRepo,
|
||||
) *Server {
|
||||
s := &Server{
|
||||
players: make(map[int64]*entity.Player),
|
||||
planets: make(map[int64]*planet.Planet),
|
||||
gameRepo: gameRepo,
|
||||
serverRepo: serverRepo,
|
||||
accountRepo: accountRepo,
|
||||
playerInfoRepo: playerInfoRepo,
|
||||
playerItemRepo: playerItemRepo,
|
||||
petRepo: petRepo,
|
||||
}
|
||||
s.initializePlanets()
|
||||
return s
|
||||
}
|
||||
|
||||
// initializePlanets 初始化所有星球
|
||||
func (s *Server) initializePlanets() {
|
||||
maps := s.gameRepo.GetAllMaps()
|
||||
for _, config := range maps {
|
||||
planet := s.generatePlanet(config)
|
||||
s.planets[planet.GetId()] = planet
|
||||
}
|
||||
}
|
||||
|
||||
// generatePlanet 根据地图配置生成星球
|
||||
func (s *Server) generatePlanet(config *mapInfo.MapXmlModel) *planet.Planet {
|
||||
entries := config.GetEntries()
|
||||
positions := make(map[int64]structs.Point)
|
||||
|
||||
if len(entries) == 0 {
|
||||
positions = make(map[int64]structs.Point)
|
||||
} else {
|
||||
for _, entry := range entries {
|
||||
positions[entry.GetFromMap()] = s.generatePoint(entry)
|
||||
}
|
||||
}
|
||||
|
||||
return planet.NewPlanet(
|
||||
s,
|
||||
int64(config.GetId()),
|
||||
config.GetName(),
|
||||
structs.Point{X: config.GetX(), Y: config.GetY()},
|
||||
positions,
|
||||
s.gameRepo.CanMapRefresh(config.GetId()),
|
||||
)
|
||||
}
|
||||
|
||||
// generatePoint 从入口配置生成点坐标
|
||||
func (s *Server) generatePoint(xml *mapInfo.EntryXmlModel) structs.Point {
|
||||
return structs.Point{X: xml.GetPosX(), Y: xml.GetPosY()}
|
||||
}
|
||||
|
||||
// GetPlayer 获取玩家信息
|
||||
func (s *Server) GetPlayer(accountID int64) (*entity.Player, error) {
|
||||
s.mutex.RLock()
|
||||
defer s.mutex.RUnlock()
|
||||
|
||||
player, exists := s.players[accountID]
|
||||
if !exists {
|
||||
return nil, errors.New("玩家不存在")
|
||||
}
|
||||
return player, nil
|
||||
}
|
||||
|
||||
// GetPlanet 获取星球信息
|
||||
func (s *Server) GetPlanet(planetID int64) (*planet.Planet, error) {
|
||||
s.mutex.RLock()
|
||||
defer s.mutex.RUnlock()
|
||||
|
||||
planet, exists := s.planets[planetID]
|
||||
if !exists {
|
||||
return nil, errors.New("星球不存在")
|
||||
}
|
||||
return planet, nil
|
||||
}
|
||||
|
||||
// GetDefaultPlanet 获取默认星球
|
||||
func (s *Server) GetDefaultPlanet() (*planet.Planet, error) {
|
||||
s.mutex.RLock()
|
||||
defer s.mutex.RUnlock()
|
||||
|
||||
planet, exists := s.planets[1] // 假设1是默认星球ID
|
||||
if !exists {
|
||||
return nil, errors.New("未找到默认星球")
|
||||
}
|
||||
return planet, nil
|
||||
}
|
||||
|
||||
// PlayerEnter 玩家加入服务器
|
||||
func (s *Server) PlayerEnter(player *entity.Player) {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
s.players[player.GetAccountID()] = player
|
||||
}
|
||||
|
||||
// PlayerOffline 玩家离线处理
|
||||
func (s *Server) PlayerOffline(player *entity.Player) {
|
||||
s.mutex.Lock()
|
||||
defer s.mutex.Unlock()
|
||||
|
||||
// 清理缓存会话数据
|
||||
if err := s.accountRepo.RemoveSessionID(player.GetSessionID()); err != nil {
|
||||
log.Printf("清除会话ID失败: %v", err)
|
||||
}
|
||||
|
||||
// 清理登录绑定服务器
|
||||
if err := s.serverRepo.CancelRecordAccount(player.GetAccountID()); err != nil {
|
||||
log.Printf("取消账号绑定失败: %v", err)
|
||||
}
|
||||
|
||||
// 从玩家列表中移除
|
||||
delete(s.players, player.GetAccountID())
|
||||
}
|
||||
|
||||
// BroadcastMessage 广播消息给所有在线玩家
|
||||
func (s *Server) BroadcastMessage(message *net.OutboundMessage) {
|
||||
s.mutex.RLock()
|
||||
defer s.mutex.RUnlock()
|
||||
|
||||
for _, player := range s.players {
|
||||
if player.IsOnline() {
|
||||
player.SendMessage(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BroadcastMessageWithFilter 按条件广播消息给在线玩家
|
||||
func (s *Server) BroadcastMessageWithFilter(message *net.OutboundMessage, filter func(*entity.Player) bool) {
|
||||
s.mutex.RLock()
|
||||
defer s.mutex.RUnlock()
|
||||
|
||||
for _, player := range s.players {
|
||||
if player.IsOnline() && filter(player) {
|
||||
player.SendMessage(message)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GeneratePetEntity 生成宠物实体
|
||||
func (s *Server) GeneratePetEntity(
|
||||
playerID int64,
|
||||
petTypeID int,
|
||||
individualValue int16,
|
||||
nature int,
|
||||
abilityTypeEnum int,
|
||||
isShiny bool,
|
||||
level int,
|
||||
) (*pet.PetEntity, error) {
|
||||
if level < 1 || level > 100 {
|
||||
return nil, fmt.Errorf("精灵等级必须在1到100之间, level: %d", level)
|
||||
}
|
||||
|
||||
petInfo, err := s.gameRepo.GetMonsterByID(petTypeID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无效的精灵ID, pet_id: %d, 错误: %v", petTypeID, err)
|
||||
}
|
||||
|
||||
firstSkillInfo, err := s.gameRepo.GetPetFirstSkillID(petTypeID, level)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("精灵没有初始技能, pet_id: %d, 错误: %v", petTypeID, err)
|
||||
}
|
||||
|
||||
zero := int16(0)
|
||||
|
||||
pet := pet.NewPetEntityBuilder()
|
||||
.WithAsset(petInfo)
|
||||
.WithLevelToExp(s.gameRepo.GetLevelToExp())
|
||||
.WithPlayerID(playerID)
|
||||
.WithCapturePlayerID(playerID)
|
||||
.WithCaptureTime(time.Now().Unix())
|
||||
.WithCaptureMap(0) // 假设0是默认地图ID
|
||||
.WithCaptureRect(0) // 假设0是默认区域
|
||||
.WithCaptureLevel(level)
|
||||
.WithIndividualValue(individualValue)
|
||||
.WithNature(nature)
|
||||
.WithAbilityTypeEnum(abilityTypeEnum)
|
||||
.WithIsShiny(isShiny)
|
||||
.WithLevel(level)
|
||||
.WithCurrentExp(0)
|
||||
.WithEvHp(zero)
|
||||
.WithEvAttack(zero)
|
||||
.WithEvDefense(zero)
|
||||
.WithEvSpecialAttack(zero)
|
||||
.WithEvSpecialDefense(zero)
|
||||
.WithEvSpeed(zero)
|
||||
.WithSkill1ID(firstSkillInfo[0].GetId())
|
||||
.WithSkill1Pp(firstSkillInfo[0].GetMaxPp())
|
||||
.WithSkill2ID(firstSkillInfo[1].GetId())
|
||||
.WithSkill2Pp(firstSkillInfo[1].GetMaxPp())
|
||||
.WithSkill3ID(firstSkillInfo[2].GetId())
|
||||
.WithSkill3Pp(firstSkillInfo[2].GetMaxPp())
|
||||
.WithSkill4ID(firstSkillInfo[3].GetId())
|
||||
.WithSkill4Pp(firstSkillInfo[3].GetMaxPp())
|
||||
.WithIndividualGuarantee(0)
|
||||
.WithNatureGuarantee(0)
|
||||
.Build()
|
||||
|
||||
if err := s.CalculatePetPanel(pet); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return pet, nil
|
||||
}
|
||||
|
||||
// CalculatePetPanel 计算宠物面板属性
|
||||
func (s *Server) CalculatePetPanel(petEntity *pet.PetEntity) error {
|
||||
natureInfo, err := s.gameRepo.GetNatureInfoByID(petEntity.GetNature())
|
||||
if err != nil {
|
||||
return fmt.Errorf("无效的性格ID, nature: %d, 错误: %v", petEntity.GetNature(), err)
|
||||
}
|
||||
|
||||
hp := util.CalculatePetHPPanelSize(
|
||||
petEntity.GetAsset().GetHp(),
|
||||
petEntity.GetIndividualValue(),
|
||||
petEntity.GetLevel(),
|
||||
petEntity.GetEvHp(),
|
||||
)
|
||||
|
||||
attack := util.CalculatePetPanelSize(
|
||||
petEntity.GetAsset().GetAtk(),
|
||||
petEntity.GetIndividualValue(),
|
||||
petEntity.GetLevel(),
|
||||
petEntity.GetEvHp(),
|
||||
natureInfo.GetAttackCorrect(),
|
||||
)
|
||||
|
||||
defense := util.CalculatePetPanelSize(
|
||||
petEntity.GetAsset().GetDef(),
|
||||
petEntity.GetIndividualValue(),
|
||||
petEntity.GetLevel(),
|
||||
petEntity.GetEvHp(),
|
||||
natureInfo.GetDefenseCorrect(),
|
||||
)
|
||||
|
||||
specialAttack := util.CalculatePetPanelSize(
|
||||
petEntity.GetAsset().GetSpAtk(),
|
||||
petEntity.GetIndividualValue(),
|
||||
petEntity.GetLevel(),
|
||||
petEntity.GetEvHp(),
|
||||
natureInfo.GetSaCorrect(),
|
||||
)
|
||||
|
||||
specialDefense := util.CalculatePetPanelSize(
|
||||
petEntity.GetAsset().GetSpDef(),
|
||||
petEntity.GetIndividualValue(),
|
||||
petEntity.GetLevel(),
|
||||
petEntity.GetEvHp(),
|
||||
natureInfo.GetSdCorrect(),
|
||||
)
|
||||
|
||||
speed := util.CalculatePetPanelSize(
|
||||
petEntity.GetAsset().GetSpd(),
|
||||
petEntity.GetIndividualValue(),
|
||||
petEntity.GetLevel(),
|
||||
petEntity.GetEvHp(),
|
||||
natureInfo.GetSpeedCorrect(),
|
||||
)
|
||||
|
||||
petEntity.SetMaxHp(hp)
|
||||
petEntity.SetCurrentHp(hp)
|
||||
petEntity.SetAttack(attack)
|
||||
petEntity.SetDefense(defense)
|
||||
petEntity.SetSpecialAttack(specialAttack)
|
||||
petEntity.SetSpecialDefense(specialDefense)
|
||||
petEntity.SetSpeed(speed)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SavePlayer 保存玩家信息到数据库
|
||||
func (s *Server) SavePlayer(player *entity.Player) (bool, error) {
|
||||
ctx := context.Background()
|
||||
tx, err := s.playerInfoRepo.BeginTransaction(ctx)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("开始事务失败: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
log.Printf("保存玩家时发生panic: %v", r)
|
||||
} else if err != nil {
|
||||
tx.Rollback()
|
||||
} else {
|
||||
tx.Commit()
|
||||
}
|
||||
}()
|
||||
|
||||
playerID := player.GetGameID()
|
||||
pets := player.GetPetBag().GetUsedPets()
|
||||
items := player.GetItemBag().GetItems()
|
||||
|
||||
// 保存玩家信息
|
||||
if err := s.playerInfoRepo.Save(ctx, tx, player); err != nil {
|
||||
return false, fmt.Errorf("保存玩家信息失败: %v", err)
|
||||
}
|
||||
|
||||
// 保存精灵信息
|
||||
if err := s.petRepo.SaveAll(ctx, tx, playerID, pets); err != nil {
|
||||
return false, fmt.Errorf("保存精灵信息失败: %v", err)
|
||||
}
|
||||
|
||||
// 保存玩家背包信息
|
||||
if err := s.playerItemRepo.SaveAll(ctx, tx, playerID, items); err != nil {
|
||||
return false, fmt.Errorf("保存背包信息失败: %v", err)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Destroy 销毁服务器,清理资源
|
||||
func (s *Server) Destroy() error {
|
||||
// 保存所有玩家数据
|
||||
s.mutex.RLock()
|
||||
for _, player := range s.players {
|
||||
go func(p *entity.Player) {
|
||||
if _, err := s.SavePlayer(p); err != nil {
|
||||
log.Printf("保存玩家 %d 数据失败: %v", p.GetAccountID(), err)
|
||||
}
|
||||
}(player)
|
||||
}
|
||||
s.mutex.RUnlock()
|
||||
|
||||
log.Println("Destroying server ...")
|
||||
return nil
|
||||
}
|
||||
83
common/socket/ServerEvent.go
Normal file
83
common/socket/ServerEvent.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package socket
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/panjf2000/gnet/v2"
|
||||
"github.com/panjf2000/gnet/v2/pkg/logging"
|
||||
)
|
||||
|
||||
func (s *Server) Boot() error {
|
||||
err := gnet.Run(s, s.addr,
|
||||
gnet.WithMulticore(true),
|
||||
gnet.WithSocketRecvBuffer(s.bufferSize))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) Stop() error {
|
||||
_ = s.eng.Stop(context.Background())
|
||||
s.workerPool.Release()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) OnBoot(eng gnet.Engine) gnet.Action {
|
||||
s.eng = eng
|
||||
|
||||
logging.Infof("syslog server is listening on %s\n", s.addr)
|
||||
|
||||
return gnet.None
|
||||
}
|
||||
|
||||
func (s *Server) OnTraffic(conn gnet.Conn) (action gnet.Action) {
|
||||
|
||||
|
||||
if s.network == "tcp" {
|
||||
return s.handleTcp(conn)
|
||||
}
|
||||
|
||||
|
||||
|
||||
return gnet.None
|
||||
}
|
||||
|
||||
|
||||
func (s *Server) handleTcp(conn gnet.Conn) (action gnet.Action) {
|
||||
for {
|
||||
data, err := s.codec.Decode(conn)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
|
||||
//client := conn.RemoteAddr().String()
|
||||
_ = s.workerPool.Submit(func() {
|
||||
s.parser(conn, data)
|
||||
})
|
||||
|
||||
return gnet.None
|
||||
}
|
||||
|
||||
if conn.InboundBuffered() > 0 {
|
||||
if err := conn.Wake(nil); err != nil { // wake up the connection manually to avoid missing the leftover data
|
||||
logging.Errorf("failed to wake up the connection, %v", err)
|
||||
return gnet.Close
|
||||
}
|
||||
}
|
||||
|
||||
return gnet.None
|
||||
|
||||
}
|
||||
|
||||
func (s *Server) parser(c gnet.Conn, line []byte) {
|
||||
|
||||
s.handler.Handle(line)
|
||||
}
|
||||
func (s *Server) Start() {
|
||||
|
||||
err := gnet.Run(s, s.network+"://"+s.addr, gnet.WithMulticore(s.multicore))
|
||||
logging.Infof("server exits with error: %v", err)
|
||||
}
|
||||
63
common/socket/ServerOption.go
Normal file
63
common/socket/ServerOption.go
Normal file
@@ -0,0 +1,63 @@
|
||||
package socket
|
||||
|
||||
import (
|
||||
"blazing/common/socket/codec"
|
||||
"blazing/common/socket/handler"
|
||||
|
||||
"github.com/panjf2000/gnet/pkg/pool/goroutine"
|
||||
"github.com/panjf2000/gnet/v2"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
gnet.BuiltinEventEngine
|
||||
eng gnet.Engine
|
||||
addr string
|
||||
network string
|
||||
multicore bool
|
||||
bufferSize int
|
||||
workerPool *goroutine.Pool
|
||||
codec codec.SocketCodec
|
||||
handler handler.Handler
|
||||
}
|
||||
|
||||
type Option func(*Server)
|
||||
|
||||
// NewServer returns a new Server
|
||||
|
||||
func NewServer(options ...Option) *Server {
|
||||
server := &Server{
|
||||
handler: handler.NewTomeeHandler(), //请求返回
|
||||
codec: codec.NewTomeeSocketCodec(), //默认解码器 len+pack
|
||||
workerPool: goroutine.Default(),
|
||||
bufferSize: 4096, //默认缓冲区大小
|
||||
multicore: true,
|
||||
}
|
||||
for _, option := range options {
|
||||
option(server)
|
||||
}
|
||||
//...
|
||||
return server
|
||||
}
|
||||
func WithSocketCodec(codec codec.SocketCodec) Option {
|
||||
return func(u *Server) {
|
||||
u.codec = codec
|
||||
}
|
||||
}
|
||||
|
||||
func WithSocketHandler(handler handler.Handler) Option {
|
||||
return func(u *Server) {
|
||||
u.handler = handler
|
||||
}
|
||||
}
|
||||
func WithBufferSize(bufferSize int) Option {
|
||||
return func(u *Server) {
|
||||
u.bufferSize = bufferSize
|
||||
}
|
||||
}
|
||||
func WithPort(port string) Option {
|
||||
return func(s *Server) {
|
||||
|
||||
s.network = "tcp"
|
||||
s.addr = ":" + port
|
||||
}
|
||||
}
|
||||
33
common/socket/codec/CrossDomain.go
Normal file
33
common/socket/codec/CrossDomain.go
Normal 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
|
||||
}
|
||||
13
common/socket/codec/SocketCodec.go
Normal file
13
common/socket/codec/SocketCodec.go
Normal 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)
|
||||
|
||||
}
|
||||
75
common/socket/codec/SocketCodec_Tomee.go
Normal file
75
common/socket/codec/SocketCodec_Tomee.go
Normal 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
|
||||
}
|
||||
6
common/socket/handler/SocketHandler.go
Normal file
6
common/socket/handler/SocketHandler.go
Normal file
@@ -0,0 +1,6 @@
|
||||
package handler
|
||||
|
||||
// Handler The handler receive every syslog entry at Handle method
|
||||
type Handler interface {
|
||||
Handle([]byte)
|
||||
}
|
||||
24
common/socket/handler/SocketHandler_Tomee.go
Normal file
24
common/socket/handler/SocketHandler_Tomee.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package handler
|
||||
|
||||
// TomeeHeader 结构体字段定义
|
||||
type TomeeHeader struct {
|
||||
Version string `json:"version"`
|
||||
UserID int `json:"userId"`
|
||||
Error int `json:"error"`
|
||||
CMDID int `json:"cmdId"`
|
||||
Result int `json:"result"`
|
||||
}
|
||||
type TomeeHandler struct {
|
||||
|
||||
}
|
||||
|
||||
func NewTomeeHandler() *TomeeHandler {
|
||||
return &TomeeHandler{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Handle entry receiver
|
||||
func (h *TomeeHandler) Handle(data []byte ) {
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user