go实现tcp游戏服务器sibo——服务器实现篇

package server

import (
    "net"
    "time"
    "sync"
    "crypto/tls"
    log "github.com/sirupsen/logrus"
    "runtime"
    "bufio"
    "strings"
    "io"
    "sibo/protocol"
    "sibo/share"
    "errors"
    "fmt"
    "sibo/proto"
    "github.com/robfig/cron"
    "path"
    "github.com/lestrrat/go-file-rotatelogs"
    "github.com/rifflock/lfshook"
)
var ErrServerClosed = errors.New("sibo: Server closed")

var shutdownPollInterval = 500 * time.Millisecond
var schuduleInterval = 1 * time.Minute

// 读写缓冲区大小
const (
    ReaderBufferSize = 1024
    WriterBufferSize = 1024
)

type Server struct {
    ln                   net.Listener
    readTimeout          time.Duration
    writeTimeout         time.Duration

    mu            sync.RWMutex
    activeSession map[ISession]struct{} // 全局连接管理器
    doneChan      chan struct{} //
    inShutdown    int32 // 监听server的关闭状态

    // TLSConfig for creating tls tcp connection.
    tlsConfig *tls.Config // tls配置
    waitGroup *sync.WaitGroup

    cron *cron.Cron // 定时任务
    scheduleSaveDuration time.Duration // 内存数据保存到数据库的定时任务的周期
}

func NewServer() *Server {
    return &Server{
        waitGroup:            &sync.WaitGroup{},
        cron:                 cron.New(),
        scheduleSaveDuration: schuduleInterval,
    }
}
// 返回服务器地址
func (s *Server) Address() net.Addr {
    s.mu.RLock()
    defer s.mu.RUnlock()
    if s.ln == nil {
        return nil
    }
    return s.ln.Addr()
}

// 设置定时任务周期
func (s *Server) SetScheduleSaveDuration(t time.Duration) {
    s.scheduleSaveDuration = t
}

func (s *Server) Serve(network, address string) (err error) {
    var ln net.Listener
    if s.tlsConfig == nil {
        ln, err = net.Listen("tcp", address)
    } else {
        l
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值