24_服务器定时发送缓冲区

根据不同的应用场景,服务器需要定时把缓冲区内的数据发送给客户端,如游戏里的消息共享,聊天时的信息传输,服务器通过定时发送数据,更精细化的控制交互过程

修改CellClient.cpp

#ifndef _CellClient_hpp_
#define _CellClient_hpp_

#include"CELL.hpp"

//把发送缓冲区内缓存的消息数据发送给客户端
#define CLIENT_SEND_BUFF_TIME 200
//客户端数据类型
class CellClient
{
public:
    //立即发送数据
    int SendDataReal(netmsg_DataHeader* header)
    {
        SendData(header);
        SendDataReal();
    }

    //立即将发送缓冲区的数据发送给客户端
    int SendDataReal()
    {
        int ret = SOCKET_ERROR;
        //缓冲区有数据
        if (_lastSendPos > 0 && SOCKET_ERROR != _sockfd)
        {
            //发送数据
            ret = send(_sockfd, _szSendBuf, _lastSendPos, 0);
            //数据尾部位置清零
            _lastSendPos = 0;
            //
            resetDTSend();
        }
        return ret;
    }


    void resetDTSend()
    {
        _dtSend = 0;
    }

    //定时发送消息检测
    bool checkSend(time_t dt)
    {
        _dtSend += dt;
        if (_dtSend >= CLIENT_SEND_BUFF_TIME)
        {
            //printf("checkSend:s=%d,time=%d\n", _sockfd, _dtSend);
            //立即将发送缓冲区的数据发送出去
            SendDataReal();
            //重置发送计时
            resetDTSend();
            return true;
        }
        return false;
    }
private:
    //上次发送消息数据的时间
    time_t _dtSend;
};

#endif // !_CellClient_hpp_

Cellsever.cpp的修改

time_t _oldTime = CELLTime::getNowInMilliSec();
void CheckTime()
{
    auto nowTime = CELLTime::getNowInMilliSec();
    auto dt = nowTime - _oldTime;
    _oldTime = nowTime;

    for (auto iter = _clients.begin(); iter != _clients.end(); )
    {
        if (iter->second->checkHeart(dt))
        {
            if (_pNetEvent)
                _pNetEvent->OnNetLeave(iter->second);
            _clients_change = true;
            delete iter->second;
            auto iterOld = iter;
            iter++;
            _clients.erase(iterOld);
            continue;
        }
        //检测完心跳后检测每个客户端缓冲区的停留时长
        iter->second->checkSend(dt);
        iter++;
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top