feat(socket): 增加连接数统计功能

- 在 Server 结构中添加 connected 字段,用于统计当前连接数
- 在 OnOpen 和 OnClose 事件处理函数中增加连接数的增减逻辑
- 添加 OnTick 方法,定期打印当前连接数
- 更新 ServerEvent 和 ServerOption 文件,集成新功能
This commit is contained in:
2025-07-07 19:58:23 +08:00
parent f0f6689424
commit 33723334f9
5 changed files with 32 additions and 10 deletions

View File

@@ -3,6 +3,8 @@ package socket
import (
"context"
"log"
"sync/atomic"
"time"
"blazing/common/data/entity"
@@ -12,13 +14,15 @@ import (
)
func (s *Server) Boot() error {
err := gnet.Run(s, s.addr,
err := gnet.Run(s, s.network+"://"+s.addr,
gnet.WithMulticore(true),
gnet.WithTicker(true),
gnet.WithSocketRecvBuffer(s.bufferSize))
if err != nil {
return err
}
// err := gnet.Run(s, s.network+"://"+s.addr, gnet.WithMulticore(s.multicore))
// logging.Infof("server exits with error: %v", err)
return nil
}
@@ -30,7 +34,8 @@ func (s *Server) Stop() error {
}
func (s *Server) OnClose(c gnet.Conn, _ error) (action gnet.Action) {
atomic.AddInt64(&s.connected, -1)
//logging.Infof("conn[%v] disconnected", c.RemoteAddr().String())
v := c.Context().(*entity.ClientData)
t := v.GetPlayer()
if t != nil {
@@ -42,6 +47,10 @@ func (s *Server) OnClose(c gnet.Conn, _ error) (action gnet.Action) {
//关闭连接
return
}
func (s *Server) OnTick() (delay time.Duration, action gnet.Action) {
logging.Infof("[connected-count=%v]", atomic.LoadInt64(&s.connected))
return 3 * time.Second, gnet.None
}
func (s *Server) OnBoot(eng gnet.Engine) gnet.Action {
s.eng = eng
@@ -50,6 +59,12 @@ func (s *Server) OnBoot(eng gnet.Engine) gnet.Action {
return gnet.None
}
func (s *Server) OnOpen(_ gnet.Conn) (out []byte, action gnet.Action) {
atomic.AddInt64(&s.connected, 1)
return nil, gnet.None
}
func (s *Server) OnTraffic(conn gnet.Conn) (action gnet.Action) {
if conn.Context() == nil {
conn.SetContext(entity.NewClientData()) //注入data
@@ -96,11 +111,6 @@ func (s *Server) parser(c gnet.Conn, line []byte) {
//todo 这里待实现注入player实体
s.handler.Handle(c, 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)
}
// 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"

View File

@@ -13,6 +13,7 @@ type Server struct {
gnet.BuiltinEventEngine
eng gnet.Engine
addr string
connected int64
network string
multicore bool
bufferSize int