前言
- 当我们在使⽤链接处理的时候,希望和链接绑定⼀些⽤户的数据,或者参数。那么我们现在可以把当前
链接设定⼀些传递参数的接⼝或者⽅法
一、实现思路
二、链接添加链接配置接⼝
- zinx/ziface/iconnection.go
package ziface
import "net"
type IConneciton interface {
Start()
Stop()
GetTCPConnection() *net.TCPConn
GetConnID() uint32
RemoteAddr() net.Addr
SendMsg(msgId uint32, data []byte) error
SetProperty(key string, value interface{})
GetProperty(key string) (interface{}, error)
RemoveProperty(key string)
}
type HandleFunc func(*net.TCPConn, []byte, int) error
三、链接实现配置接口
type Connection struct {
TcpServer ziface.IServer
Conn *net.TCPConn
ConnID uint32
isClosed bool
ExitChan chan bool
msgChan chan []byte
MsgHandler ziface.IMsgHandle
property map[string]interface{}
propertyLock sync.RWMutex
}
func NewConnection(server ziface.IServer, conn *net.TCPConn, connID uint32, msgHandler ziface.IMsgHandle) *Connection {
c := &Connection{
TcpServer: server,
Conn: conn,
ConnID: connID,
MsgHandler: msgHandler,
isClosed: false,
msgChan: make(chan []byte),
ExitChan: make(chan bool, 1),
property: make(map[string]interface{}),
}
c.TcpServer.GetConnMgr().Add(c)
return c
}
func (c *Connection) SetProperty(key string, value interface{}) {
c.propertyLock.Lock()
defer c.propertyLock.Unlock()
c.property[key] = value
}
func (c *Connection) GetProperty(key string) (interface{}, error) {
c.propertyLock.RLock()
defer c.propertyLock.RUnlock()
if value, ok := c.property[key]; ok {
return value, nil
} else {
return nil, errors.New("no property found")
}
}
func (c *Connection) RemoveProperty(key string) {
c.propertyLock.Lock()
defer c.propertyLock.Unlock()
delete(c.property, key)
}
四、测试链接属性配置
- myDemo/zinxV1.0/Server.go:测试的时候在创建链接之后设置属性,在链接断开之前读取属性
func DoConnectionBegin(conn ziface.IConneciton) {
fmt.Println("===> DoConnectionBegin is Called ... ")
if err := conn.SendMsg(202, []byte("DoConnection BEGIN")); err != nil {
fmt.Println(err)
}
fmt.Println("Set conn property....")
conn.SetProperty("Name", "刘丹冰-Aceld-IT无崖子")
conn.SetProperty("GitHub", "https://github.com/aceld")
conn.SetProperty("Home", "https://legacy.gitbook.com/@aceld")
conn.SetProperty("Blog", "https://www.jianshu.com/u/35261429b7f1")
}
func DoConnectionLost(conn ziface.IConneciton) {
fmt.Println("===> DoConnectionLost is Called ...")
fmt.Println("conn ID = ", conn.GetConnID(), " is Lost...")
if name, err := conn.GetProperty("Name"); err == nil {
fmt.Println("Name = ", name)
}
if home, err := conn.GetProperty("Home"); err == nil {
fmt.Println("Home = ", home)
}
if github, err := conn.GetProperty("GitHub"); err == nil {
fmt.Println("GitHub = ", github)
}
if blog, err := conn.GetProperty("Blog"); err == nil {
fmt.Println("Blog = ", blog)
}
}
五、目录结构
六、完整源码
下载zinxV1.0