使用GoLang开发游戏服务器(十)

连接属性开发

  • 有时候需要允许用户在外部设置connection的属性
  • 在IConnection中定义方法
    在这里插入图片描述
  • 在Connection结构体中定义属性,并实现方法
    在这里插入图片描述
func (c *Connection) SetProperty(key string, value interface{}) {
	c.PropertyLock.Lock()
	defer c.PropertyLock.Unlock()
	c.Properties[key] = value
}

func (c *Connection) GetProperty(key string) (interface{}, error) {
	c.PropertyLock.RLock()
	defer c.PropertyLock.RUnlock()
	if val, ok := c.Properties[key]; ok {
		return val, nil
	}
	return nil, errors.New("Properties Not Have Key:" + key)
}

func (c *Connection) RemoveProperty(key string) {
	c.PropertyLock.Lock()
	defer c.PropertyLock.Unlock()
	delete(c.Properties, key)
}

外部使用测试

func ConnectionStart(conn ziface.IConnection) {
	fmt.Println("==>ConnectionStart Start...")
	if err := conn.SendMsg(202, []byte("Do Connection Begin...")); err != nil {
		fmt.Println(err)
		return
	}
	conn.SetProperty("Name", "zzs")
	conn.SetProperty("QQ", "3192766733")
}

func ConnectionStop(conn ziface.IConnection) {
	fmt.Println("==>ConnectionStop Stop...")
	fmt.Println("ConnID:", conn.GetConnectionID(), "Is Lost...")
	if val, err := conn.GetProperty("Name"); err == nil {
		fmt.Println(val)
	}
	if val, err := conn.GetProperty("QQ"); err == nil {
		fmt.Println(val)
	}
}

func main() {
	s := znet.NewServer("[zinxV1.0]ServerApp")

	s.SetConnectionStart(ConnectionStart)
	s.SetConnectionStop(ConnectionStop)

	s.AddRouter(1, &PingRouter{})
	s.AddRouter(2, &HelloRouter{})
	s.Serve()
}

至此GoLang游戏服务器开发完毕!!!