You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.4 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package server
import (
"sync"
protocolpkg "github.com/noahlann/nnet/pkg/protocol"
unpackerpkg "github.com/noahlann/nnet/pkg/unpacker"
)
// unpackerInfo 拆包器信息
type unpackerInfo struct {
unpacker unpackerpkg.Unpacker
}
// unpackerManager 拆包器管理器每个连接一个unpacker
type unpackerManager struct {
unpackers map[string]*unpackerInfo
mu sync.RWMutex
}
// newUnpackerManager 创建拆包器管理器
func newUnpackerManager() *unpackerManager {
return &unpackerManager{
unpackers: make(map[string]*unpackerInfo),
}
}
// getOrCreateUnpacker 获取或创建连接的拆包器
func (m *unpackerManager) getOrCreateUnpacker(connID string, protocol protocolpkg.Protocol) unpackerpkg.Unpacker {
m.mu.RLock()
info, exists := m.unpackers[connID]
m.mu.RUnlock()
if exists {
return info.unpacker
}
if protocol == nil {
return nil
}
withUnpacker, ok := interface{}(protocol).(interface {
Unpacker() unpackerpkg.Unpacker
})
if !ok {
return nil
}
unpacker := withUnpacker.Unpacker()
if unpacker == nil {
return nil
}
m.mu.Lock()
defer m.mu.Unlock()
if existing, ok := m.unpackers[connID]; ok {
return existing.unpacker
}
m.unpackers[connID] = &unpackerInfo{unpacker: unpacker}
return unpacker
}
// removeUnpacker 移除连接的拆包器
func (m *unpackerManager) removeUnpacker(connID string) {
m.mu.Lock()
delete(m.unpackers, connID)
m.mu.Unlock()
}