服务器和客户端简单的使用select网络模型(四)

在三的基础上增加多线程,提高了服务器处理客户端数据的能力,客户端尽可能的实现了高并发,此版本只是客户端给服务器发消息,服务器不给客户端回消息。

Server部分:一共4个文件(server.cpp,EasyTcpServer.hpp,MessageHeader.hpp和CELLTimestamp.hpp)

server.cpp:

服务器和客户端简单的使用select网络模型(四)
#include"EasyTcpServer.hpp"
#include<thread>

bool g_bRun = true;
void CmdThread()
{
    while (true)
    {
        char cmdBuf[256] = {};
        //scanf("%s", cmdBuf);

        if (0 == strcmp(cmdBuf, "exit")) {

            g_bRun = false;
            printf("退出cmdThread线程\n");
            break;
        }
        else
            printf("不支持的命令。 \n");
    }
}

int main()
{
    EsayTcpServer server;
    server.initSocket();
    server.Bind(nullptr, 10000);
    server.Listen(5);
    server.Start(4);
    /*std::thread t1(CmdThread);
    t1.detach();*/
    while (g_bRun)
    {
        server.OnRun();
    }
    server.Close();
    printf("已退出\n");

    return 0;
}
View Code

EasyTcpServer.hpp:

服务器和客户端简单的使用select网络模型(四)
#ifndef _EASY_TCP_SERVER_HPP_
#define _EASY_TCP_SERVER_HPP_
#define _AFXDLL
#ifdef _WIN32
    #define FD_SETSIZE      5000
    #include"afx.h"
    #include<windows.h>
    #include "WinSock2.h"
#else
    #include<unistd.h>
    #include<arpa/inet.h>
    #include<string.h>

#define SOCKET int
#define INVALID_SOCKET  (SOCKET)(~0)
#define SOCKET_ERROR            (-1)
#endif
#include<iostream>
#include<vector>
#include<stdlib.h>
#include<thread>
#include<mutex>
#include<atomic>


#include"MessageHeader.hpp"
#include "CELLTimestamp.hpp"


#ifndef RECV_BUFF_SIZE
#define RECV_BUFF_SIZE 10240        //接收缓冲区的大小
#endif

//客户端数据类型
class ClientSocket
{
public:
    ClientSocket(SOCKET sockfd = INVALID_SOCKET)
    {
        _sockfd = sockfd;
        ZeroMemory(_szMsgBuf, 0, sizeof(_szMsgBuf));
        _lastPos = 0;
    }
    ~ClientSocket()
    {
    }


    SOCKET sockfd()
    {
        return _sockfd;
    }

    char * msgBuf()
    {
        return _szMsgBuf;
    }

    int getLastPos()
    {
        return _lastPos;
    }

    void setLastPos(int pos)
    {
        _lastPos = pos;
    }

    //发送数据给指定的socket
    int SendData(DataHeader* header)
    {
        if (header)
            send(_sockfd, (const char*)header, header->dataLength, 0);
        return SOCKET_ERROR;
    }

private:
    SOCKET _sockfd;
    char _szMsgBuf[RECV_BUFF_SIZE * 5];
    //消息缓冲区数据尾部位置
    int _lastPos;
};

//网络事件接口
class INetEvent
{
public:
    //客户端加入事件
    virtual void OnNetJoin(ClientSocket* pClient) = 0;
    //客户端离开事件
    virtual void OnNetLeave(ClientSocket* pClient) = 0;
    //客户端消息事件
    virtual void OnNetMsg(ClientSocket* pClient, DataHeader* header) = 0;
private:

};


class CellServer
{
public:
    
    CellServer(SOCKET sock = INVALID_SOCKET)
    {
        _sock = sock;
        _pThread = nullptr;
        _pNetEvnet = nullptr;
    }
    ~CellServer()
    {
        if (_pThread)
        {
            _pThread = nullptr;
        }
        if (_pNetEvnet)
        {
            _pNetEvnet = nullptr;
        }
        Close();
        _sock = INVALID_SOCKET;
    }

    void setEvnetObj(INetEvent* event)
    {
        _pNetEvnet = event;
    }
    //是否在工作中
    bool isRun()
    {
        return _sock != INVALID_SOCKET;
    }

    bool OnRun()
    {
        while(isRun())
        {
            if (_clientsBuff.size() > 0)
            {
                std::lock_guard<std::mutex> lock(_mutex);
                for (auto pClient : _clientsBuff)
                {
                    _clients.push_back(pClient);
                }
                _clientsBuff.clear();
            }
            if (_clients.empty())
            {
                //等待1毫秒
                std::chrono::milliseconds t(1);
                std::this_thread::sleep_for(t);
                continue;
            }
                
            fd_set fdRead;
            /*fd_set fdWrite;
            fd_set fdExp;*/
            FD_ZERO(&fdRead);
            /*FD_ZERO(&fdWrite);
            FD_ZERO(&fdExp);*/

            //将要监听的socket添加到数组
            //FD_SET(_sock, &fdRead);
            /*FD_SET(_sock, &fdWrite);
            FD_SET(_sock, &fdExp);*/


            //只监视连接的客户端的socket
            
            //每次进来都把所有要监视的socket添加到相应的数组中
            /*for (std::vector<ClientSocket*>::iterator it = _clients.begin(); it != _clients.end(); it++)
            {
                FD_SET((*it)->sockfd(), &fdRead);
                if (maxSock < (*it)->sockfd())
                {
                    maxSock = (*it)->sockfd();
                }
            }*/
            SOCKET maxSock = _clients[0]->sockfd();
            for (int n = (int)_clients.size() - 1; n >= 0; n--)
            {
                FD_SET(_clients[n]->sockfd(), &fdRead);
                if (maxSock < _clients[n]->sockfd())
                {
                    maxSock = _clients[n]->sockfd();
                }
            }

            //开始查询,会清空3个数组所有的socket,然后如果哪个socket有事件发送,则会把此socket放入到数组返回
            //当有客户端连接或者客户端发送消息都会进来
            //timeval time = { 2, 0 };
            /*int select(
            IN int nfds, //windows下无意义,linux有意义IN OUT fd_set* readfds,      //检查可读性
            IN OUT fd_set* writefds,    //检查可写性
            IN OUT fd_set* exceptfds,  //例外数据
            IN const struct timeval* timeout);  //函数的返回时间*/
            int ret = select(maxSock + 1, &fdRead, nullptr, nullptr, nullptr);
            if (ret < 0)
            {
                printf("select任务结束\n");
                Close();
                return false;
            }

            for (int n = (int)_clients.size() - 1; n >= 0; n--)
            {
                if (FD_ISSET(_clients[n]->sockfd(), &fdRead))
                {
                    if (-1 == RecvData(_clients[n]))
                    {
                        auto iter = _clients.begin() + n;
                        if (iter != _clients.end())
                        {
                            if (_pNetEvnet)
                                _pNetEvnet->OnNetLeave(_clients[n]);
                            delete _clients[n];
                            _clients.erase(iter);
                        }
                    }

                }
            }

            /*for (size_t n = 0; n < fdRead.fd_count; n++)
            {
                if (_clients.size()>n)
                {
                    if (FD_ISSET(_clients[n]->sockfd(), &fdRead))
                    if (-1 == RecvData(_clients[n]))
                    {
                        auto iter = _clients.begin() + n;
                        if (iter != _clients.end())
                        {
                            if (_pNetEvnet)
                                _pNetEvnet->OnLeave(_clients[n]);
                            delete _clients[n];
                            _clients.erase(iter);
                        }
                    }
                }
            }*/
        }
    }

    char _szRecv[RECV_BUFF_SIZE] = {};
     //接受数据,处理粘包,拆分包
    int RecvData(ClientSocket* pClient)
    {
        //接受客户端请求数据
        int nLen = (int)recv(pClient->sockfd(), _szRecv, RECV_BUFF_SIZE, 0);
        if (nLen <= 0)
        {
            //printf("客户端<socket=%d>已退出,任务结束\n", pClient->sockfd());
            return -1;
        }
        memcpy(pClient->msgBuf() + pClient->getLastPos(), _szRecv, nLen);
        pClient->setLastPos(pClient->getLastPos() + nLen);
        //判断消息缓冲区的数据长度大于消息头
        while (pClient->getLastPos() >= sizeof(DataHeader))
        {
            DataHeader* header = (DataHeader*)pClient->msgBuf();
            //判断消息缓冲区的数据长度大于消息体
            if (pClient->getLastPos() >= header->dataLength)
            {
                //剩余未处理消息缓冲区数据的长度
                int nSize = pClient->getLastPos() - header->dataLength;
                OnNetMsg(pClient, header);
                //将未处理的数据前移
                memcpy(pClient->msgBuf(), pClient->msgBuf() + header->dataLength, nSize);
                pClient->setLastPos(nSize);
            }
            else
            {
                //剩余数据小于一个消息体的大小
                break;
            }
        }
        return 0;
    }

     //响应网络消息
    virtual void OnNetMsg(ClientSocket* pClient, DataHeader* header)
    {
        _pNetEvnet->OnNetMsg(pClient, header);

        switch (header->cmd)
        {
        case CMD_LOGIN:
        {
                          //Login* login = (Login*)header;
                          ////printf("收到命令  用户名:%s密码%s\n", login->userName, login->PassWord);
                          //LoginResult ret = {};
                          //ret.result = 0;
                          //pClient->SendData(&ret);
        }
        break;
        case CMD_LOGOUT:
        {
                           //Logout* loginOut = (Logout*)header;
                           ////printf("收到命令: 数据长度:%d 用户名:%s密码%s\n", loginOut->dataLength, loginOut->userName);
                           //LogOutResult retOut = {};
                           //retOut.result = 0;

                           //SendData(cSock, &retOut);
        }
        break;
        case CMD_ERROR:
        {
                          printf("<socket = %d>收到服务端消息:CMD_ERROR,数据长度:%d\n", _sock, header->dataLength);
                          
        }
        break;
        default:
        {
                   printf("<socket = %d>收到未定义的消息,数据长度:%d\n", _sock, header->dataLength);
                   
        }
        break;
        }
    }

    //关闭socket
    void Close()
    {
        if (_sock != INVALID_SOCKET) {
#ifdef _WIN32
            for (int n = _clients.size() - 1; n >= 0; n--)
            {
                closesocket(_clients[n]->sockfd());
                if (_clients[n] != NULL)
                {
                    delete _clients[n];
                }
            }
            closesocket(_sock);
#else
            for (int n = _clients.size() - 1; n >= 0; n--)
            {
                close(_clients[n]->sockfd());
                if (_clients[n] != NULL)
                {
                    delete _clients[n];
                }
            }
#endif
            _clients.clear();
        }
    }

    void addClient(ClientSocket* pClient)
    {
        std::lock_guard<std::mutex> lock(_mutex);
        _clientsBuff.push_back(pClient);
    }

    void Start()
    {
        _pThread = new std::thread(std::mem_fun(&CellServer::OnRun), this);
    }

    size_t getClinetCount() 
    {
        return _clients.size() + _clientsBuff.size();
    }

private:
    SOCKET _sock;
    //客户端正式队列
    std::vector<ClientSocket*> _clients;
    //客户端缓冲队列
    std::vector<ClientSocket*> _clientsBuff;
    //缓冲队列的锁
    std::mutex _mutex;
    std::thread* _pThread;
    INetEvent* _pNetEvnet;
public:
};

class EsayTcpServer:public INetEvent
{
public:
    SOCKET _sock;
    std::vector<CellServer*>_cellServers;
    CELLTimestamp _tTime;
    std::atomic_int _recvCount;
    std::atomic_int _clientCount;
    
public:
    EsayTcpServer()
    {
        _sock = INVALID_SOCKET;
        _recvCount = 0;
        _clientCount = 0;
    }
    virtual ~EsayTcpServer()
    {
        Close();
    }

    //初始化Socket
    SOCKET initSocket()
    {
#ifdef _WIN32
        //启动Windows socket 2.x环境
        WORD ver = MAKEWORD(2, 2);
        WSADATA dat;

        WSAStartup(ver, &dat);
#endif
         //建立一个socket
        if (INVALID_SOCKET != _sock)
        {
            printf("<sock=%d>关闭之前的连接...\n", _sock);
            Close();
        }
        _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

        if (INVALID_SOCKET == _sock)
            printf("错误,创建Socket失败...\n");
        else
            printf("建立Socket成功...\n");
        return _sock;
    }
    //绑定端口
    int Bind(const char *ip, unsigned short port)
    {
        sockaddr_in sin = {};
        sin.sin_family = AF_INET;
        sin.sin_port = htons(port);    //host to net unsigned short

#ifdef _WIN32
        if (ip != NULL)
        {
            sin.sin_addr.S_un.S_addr = inet_addr(ip);
        }
        else
        {
            sin.sin_addr.S_un.S_addr = INADDR_ANY;     //本机上的外网和局域网ip任意一个拿来用 
        }

#else
        if (ip != NULL)
        {
            sin.sin_addr.s_addr = inet_addr(ip);     //本机上的外网和局域网ip任意一个拿来用
        }
        else
        {
            sin.sin_addr.s_addr = INADDR_ANY;     //本机上的外网和局域网ip任意一个拿来用 
        }

#endif
        //2绑定
        if (SOCKET_ERROR == bind(_sock, (sockaddr *)&sin, sizeof(sockaddr_in)))
        {
            TRACE(_T("ERROR:绑定socket失败\n"));
            return 0;
        }
    }
    //监听端口
    int Listen(int n)
    {
        int ret = listen(_sock, n);
        if (SOCKET_ERROR == ret)
        {
            TRACE(_T("ERROR:socket监听失败"));
        }
        else
        {
            printf("监听开始\n");
        }
        return ret;
    }
    //接受客户端连接
    SOCKET Accept()
    {
        //4接收客户端连接
        sockaddr_in clientAddr = {};
        int nAddrLen = sizeof(sockaddr_in);
        SOCKET cSock = INVALID_SOCKET;
        cSock = accept(_sock, (sockaddr*)&clientAddr, &nAddrLen);
        if (INVALID_SOCKET == cSock)
        {
            printf("接收客户端无效\n");
        }
        else
        {
            addClientToSellServer(new ClientSocket(cSock));
            //printf("第<%d>个客户端加入socket = %d,ip:%s\n", _clients.size(), cSock, inet_ntoa(clientAddr.sin_addr));
        }
        return cSock;
    }

    void addClientToSellServer(ClientSocket* pClient)
    {
        //查找客户数量最少的CellServer消息处理对象
        auto pMinServer = _cellServers[0];
        for (auto pCellServer : _cellServers)
        {
            if (pMinServer->getClinetCount() > pCellServer->getClinetCount())
            {
                pMinServer = pCellServer;
            }
        }
        pMinServer->addClient(pClient);
        OnNetJoin(pClient);
    }

    void Start(int nCellServer)
    {
        for (int n = 0; n < nCellServer; n++)
        {
            auto ser = new CellServer(_sock);
            _cellServers.push_back(ser);
            //注册网络事件接受对象
            ser->setEvnetObj(this);
            ser->Start();
        }
    }
    //关闭socket
    void Close()
    {
        if (_sock != INVALID_SOCKET) 
        {
#ifdef _WIN32
            closesocket(_sock);
            WSACleanup();
#else
            close(_sock);    
#endif
        }
    }

    int nCount = 0;
    //处理网络消息
    bool OnRun()
    {
        if (isRun())
        {
            time4msg();
            fd_set fdRead;
            fd_set fdWrite;
            fd_set fdExp;
            FD_ZERO(&fdRead);
            //FD_ZERO(&fdWrite);
            //FD_ZERO(&fdExp);

            //将要监听的socket添加到数组
            FD_SET(_sock, &fdRead);
            //FD_SET(_sock, &fdWrite);
            //FD_SET(_sock, &fdExp);


            //开始查询,会清空3个数组所有的socket,然后如果哪个socket有事件发送,则会把此socket放入到数组返回
            //当有客户端连接或者客户端发送消息都会进来
            timeval time = { 0, 10 };
            /*int select(
            IN int nfds, //windows下无意义,linux有意义IN OUT fd_set* readfds,      //检查可读性
            IN OUT fd_set* writefds,    //检查可写性
            IN OUT fd_set* exceptfds,  //例外数据
            IN const struct timeval* timeout);  //函数的返回时间*/
            int ret = select(_sock + 1, &fdRead, nullptr, nullptr, &time);
            if (ret < 0)
            {
                printf("Accept   select任务结束\n");
                Close();
                return false;
            }
            if (FD_ISSET(_sock, &fdRead))
            {
                FD_CLR(_sock, &fdRead);
                //4接收客户端连接
                Accept();
            }
        }
    }
    //是否在工作中
    bool isRun()
    {
        return _sock != INVALID_SOCKET;
    }
    // 计算收包个数
    virtual void time4msg()
    {
        auto t1 = _tTime.getElapsedSecond();
        if (t1 >= 1.0)
        {
            printf("time = <%lf>, socket<%d>, clients<%d>, recvCount<%d>\n", t1, _sock, _clientCount, (int)(_recvCount / t1));
            _recvCount = 0;
            _tTime.update();
        }
    }

    //只会被一个线程调用,安全
    virtual void OnNetJoin(ClientSocket* pClient)
    {
        _clientCount++;
    }

    //cellServer 4 多个线程调用,不安全,如果只开启1个cellServer就是安全的
    virtual void OnNetLeave(ClientSocket* pClient)
    {
        _clientCount--;
    }

    //cellServer 4 多个线程调用,不安全,如果只开启1个cellServer就是安全的
    virtual void OnNetMsg(ClientSocket* pClient, DataHeader* header)
    {
        _recvCount++;
    }
    
private:

};

#endif
View Code

MessageHeader.hpp:

服务器和客户端简单的使用select网络模型(四)
#ifndef _MessageHeader_hpp_
#define _MessageHeader_hpp_
enum CMD
{
    CMD_LOGIN,
    CMD_LOGIN_RESULT,
    CMD_LOGOUT,
    CMD_LOGOUT_RESULT,
    CMD_NEW_USER_JOIN,
    CMD_ERROR,
};
// 消息头
struct DataHeader
{
    DataHeader()
    {
        dataLength = sizeof(DataHeader);
        cmd = CMD_ERROR;
    }
    short dataLength;
    short cmd;
};
struct Login :public DataHeader
{
    Login()
    {
        dataLength = sizeof(Login);
        cmd = CMD_LOGIN;
    }
    char userName[32];
    char PassWord[32];
    char data[92];
};

struct LoginResult : public DataHeader
{
    LoginResult()
    {
        dataLength = sizeof(LoginResult);
        cmd = CMD_LOGIN_RESULT;
        result = 0;
    }
    char data[92];
    int result;
};

struct Logout :public DataHeader
{
    Logout()
    {
        dataLength = sizeof(Logout);
        cmd = CMD_LOGOUT;
    }
    char userName[32];
};

struct LogOutResult :public DataHeader
{
    LogOutResult()
    {
        dataLength = sizeof(LogOutResult);
        cmd = CMD_LOGOUT_RESULT;
        result = 0;
    }
    int result;
};

struct NewUserJoin :public DataHeader
{
    NewUserJoin()
    {
        dataLength = sizeof(NewUserJoin);
        cmd = CMD_NEW_USER_JOIN;
        sock = 0;
    }
    int sock;
};
#endif
View Code

CELLTimestamp.hpp:

服务器和客户端简单的使用select网络模型(四)
#ifndef _CELL_TIMESTAMP_HPP_
#define _CELL_TIMESTAMP_HPP_

#include<chrono>
using namespace std::chrono;
class CELLTimestamp
{
public:
    CELLTimestamp()
    {
        update();
    }
    ~CELLTimestamp()
    {
    }

    void update()
    {
        _begin = high_resolution_clock::now();
    }

    //获取当前秒
    double getElapsedSecond()
    {
        return getElapsedTimeInMicroSec()*0.000001;
    }

    //获取毫秒
    double getElapsedTimeInMilliSec()
    {
        return getElapsedTimeInMicroSec()*0.001;
    }

    //获取微妙
    long long getElapsedTimeInMicroSec()
    {
        return duration_cast<microseconds>(high_resolution_clock::now() - _begin).count();
    }
private:
protected:
    time_point<high_resolution_clock> _begin;

};
#endif
View Code

 

 

Client部分:一共3个文件(Client.cpp,EasyTcpClient.hpp和MessageHeader.hpp)

Client.cpp:

服务器和客户端简单的使用select网络模型(四)
#define _CRT_SECURE_NO_WARNINGS
#include <thread>
#include "EasyTcpClient.hpp"
#include"CELLTimestamp.hpp"
#pragma comment(lib, "ws2_32.lib")

#define CONNECT_COUNT  1

bool g_bRun = true;
//客户端数量
const int cCount = 10000;
//线程数量
const int tCount = 4;

EasyTcpClient* client[cCount];
void cmdThread()
{
    while (true) 
    {
        char cmdBuf[256] = {};
        scanf("%s", cmdBuf);

        if (0 == strcmp(cmdBuf, "exit")) {

            g_bRun = false;
            printf("退出cmdThread线程\n");
            break;
        }
        else
            printf("不支持的命令。 \n");
    }
}

void sendThread(int id)
{
    printf("thread<%d> start\n", id);
    //4个线程 ID:1-4
    int c = cCount / tCount;
    int begin = (id - 1)*c;
    int end = id*c;

    for (size_t i = begin; i < end; i++)
    {
        if (!g_bRun)
        {
            return ;
        }
        client[i] = new EasyTcpClient();
    }
    for (size_t i = begin; i < end; i++)
    {
        if (!g_bRun)
        {
            return ;
        }
        client[i]->Connect("127.0.0.1", 10000);
    }
    printf("thread<%d>, connect<begin>:%d ,<end>:%d\n", id, begin, end);

    std::chrono::milliseconds t(5000);
    std::this_thread::sleep_for(t);


    Login login[10];
    for (int n = 0; n < 20; n++)
    {
        strcpy(login[n].userName, "lyd");
        strcpy(login[n].PassWord, "lydmm");
    }

    /*Login login;
    strcpy(login.userName, "lyd");
    strcpy(login.PassWord, "lydmm");*/
    
    const int nLen = sizeof(login);

    CELLTimestamp _tTime;
    while (g_bRun)
    {
        
        for (size_t i = begin; i < end; i++)
        {
            //client[i]->OnRun();
            client[i]->SendData(login, nLen);
        }
    }
    for (size_t i = begin; i < end; i++)
    {
        client[i]->Close();
        delete client[i];
    }
    printf("thread<%d> exit\n", id);
}

int main()
{
    std::thread t(cmdThread);
    t.detach();   // 线程分离

    //启动发送线程
    for (int n = 0; n < tCount; n++)
    {
        std::thread t1(sendThread, n + 1);
        t1.detach();
    }
    while (g_bRun)
    {
        Sleep(100);
    }
    
    printf("已退出。 \n");
    return 0;
}
View Code

EasyTcpClient.hpp:

服务器和客户端简单的使用select网络模型(四)
#pragma once
#ifdef _WIN32
#include <WinSock2.h>
#include <windows.h>
#include "MessageHeader.hpp"
#include <stdio.h>
#else
#include<unistd.h>
#include<arpa/inet.h>
#include<string.h>
#define SOCKET int
#define INVALID_SOCKET (SOCKET)(~0)
#define SOCKET_ERROR           (-1)
#include <stdio.h>


#endif

#define RECV_BUFF_SIZE   10240

class EasyTcpClient
{
public:
    SOCKET _sock;
    //接受缓冲区
    char _szRecv[RECV_BUFF_SIZE];
    //第二缓冲区,消息缓冲区
    char _szMsgBuf[RECV_BUFF_SIZE * 5];
    //消息缓冲区的大小
    int _lastPos = 0;

    bool _isConnect;
public:
    EasyTcpClient() 
    {
        _sock = INVALID_SOCKET;
    }
    virtual ~EasyTcpClient() 
    {
        Close();
    }
    // 初始化socket

    void initSocket() 
    {
        // 启动Windows socket 2.x环境
#ifdef _WIN32
        WORD ver = MAKEWORD(2, 2);
        WSADATA dat;

        WSAStartup(ver, &dat);
#endif
        //----------------
        // 建立一个socket
        if (INVALID_SOCKET != _sock) 
        {
            printf("<sock=%d>关闭之前的连接...\n", _sock);
            Close();
        }
        _sock = socket(AF_INET, SOCK_STREAM, 0);

        if (INVALID_SOCKET == _sock)
            printf("错误,创建Socket失败...\n");
        //else
            //printf("建立Socket成功...\n");
    }
    // 连接服务器
    int Connect(const char* ip, unsigned short port) 
    {
        if (INVALID_SOCKET == _sock) 
        {
            initSocket();
        }
        // 连接服务器 connect
        sockaddr_in _sin = {};
        _sin.sin_family = AF_INET;
        _sin.sin_port = htons(port);
#ifdef _WIN32
        _sin.sin_addr.S_un.S_addr = inet_addr(ip);
#else
        _sin.sin_addr.s_addr = inet_addr(ip);
#endif
        int ret = connect(_sock, (sockaddr*)&_sin, sizeof(sockaddr_in));
        if (SOCKET_ERROR == ret)
            printf("连接服务器错误...\n");
        /*else
            printf("连接服务器成功...\n");*/
        return ret;
    }
    void Close() 
    {
        if (_sock != INVALID_SOCKET) {
#ifdef _WIN32
            closesocket(_sock);
            WSACleanup();
#else
            close(_sock);
#endif
            _sock = INVALID_SOCKET;
        }
    }
    // 发送数据
    // 接受数据
    // 处理网络消息
    bool OnRun() 
    {
        if (isRun()) 
        {
            fd_set fdReads;
            FD_ZERO(&fdReads);
            FD_SET(_sock, &fdReads);
            timeval t = { 0, 0 };
            int ret = select(_sock + 1, &fdReads, 0, 0, &t);
            if (ret < 0) 
            {
                printf("<socket=%d>select任务结束\n", _sock);
                return false;
            }
            if (FD_ISSET(_sock, &fdReads))
            {
                FD_CLR(_sock, &fdReads);
                if (-1 == RecvData(_sock)) 
                {
                    printf("<socket=%d>select任务结束2\n", _sock);
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    bool isRun() 
    {
        return _sock != INVALID_SOCKET;
    }
    // 接受数据,处理粘包,拆分包
    int RecvData(SOCKET _cSock)
    {
        // 缓冲区
        //ZeroMemory(_szRecv, sizeof(_szRecv));
        int nLen = recv(_cSock, (char*)&_szRecv, RECV_BUFF_SIZE, 0);
        if (nLen > 0)
        {
            memcpy(_szMsgBuf + _lastPos, _szRecv, nLen);
            _lastPos += nLen;
            //判断消息缓冲区的数据长度大于消息头
            while (_lastPos >= sizeof(DataHeader))
            {
                DataHeader* header = (DataHeader*)_szMsgBuf;
                //判断消息缓冲区的数据长度大于消息体
                if (_lastPos >= header->dataLength)
                {
                    //剩余未处理消息缓冲区数据的长度
                    int nSize = _lastPos - header->dataLength;
                    OnNetMsg(header);
                    //将未处理的数据前移
                    memcpy(_szMsgBuf, _szMsgBuf + header->dataLength, nSize);
                    _lastPos = nSize;
                }
                else
                {
                    //剩余数据小于一个消息体的大小
                    break;
                }
            }
        }
        return 0;
    }
    // 响应网络
    void OnNetMsg(DataHeader* header) 
    {
        switch (header->cmd) 
        {
        case CMD_LOGIN_RESULT: 
        {
            LoginResult* login = (LoginResult*)header;
            //printf("收到服务端消息:CMD_LOGIN_RESULT,数据长度:%d\n", header->dataLength);
            break;
        }

        case CMD_LOGOUT_RESULT: 
        {
            LogOutResult* logout = (LogOutResult*)header;
            //printf("收到服务端消息:CMD_LOGOUT_RESULT,数据长度:%d\n", header->dataLength);
            break;
        }

        case CMD_NEW_USER_JOIN: 
        {
            NewUserJoin* userJoin = (NewUserJoin*)header;
            //printf("收到服务端消息:CMD_NEW_USER_JOIN,数据长度:%d\n", header->dataLength);
            break;
        }
        case CMD_ERROR:
        {
            printf("<socket = %d>收到服务端消息:CMD_ERROR,数据长度:%d\n", _sock, header->dataLength);
            break;
        }
        default:
        {
            printf("<socket = %d>收到未定义的消息,数据长度:%d\n", _sock, header->dataLength);
            break;
        }
        }
    }


    void CloseSocket()
    {
        if (_sock != INVALID_SOCKET)
        {
#ifdef _WIN32
            closesocket(_sock);
            WSACleanup();
#else
            close(_sock);
#endif
            _sock = INVALID_SOCKET;
            _isConnect = false;
        }
    }

    // 发送数据
    int SendData(DataHeader* header, int nLen)
    {
        int ret = SOCKET_ERROR;
        if (isRun() && header)
        {
            int ret = send(_sock, (const char*)header, nLen, 0);
            if (ret == SOCKET_ERROR)
            {
                CloseSocket();
                printf("Client:socket<%d>发送数据失败\n", _sock);
            }
            else
                return ret;
        }
        return SOCKET_ERROR;
    }
};
View Code

MessageHeader.hpp:

服务器和客户端简单的使用select网络模型(四)
#ifndef _MessageHeader_hpp_
#define _MessageHeader_hpp_
enum CMD
{
    CMD_LOGIN,
    CMD_LOGIN_RESULT,
    CMD_LOGOUT,
    CMD_LOGOUT_RESULT,
    CMD_NEW_USER_JOIN,
    CMD_ERROR,
};
// 消息头
struct DataHeader
{
    DataHeader()
    {
        dataLength = sizeof(DataHeader);
        cmd = CMD_ERROR;
    }
    short dataLength;
    short cmd;
};
struct Login :public DataHeader
{
    Login()
    {
        dataLength = sizeof(Login);
        cmd = CMD_LOGIN;
    }
    char userName[32];
    char PassWord[32];
    char data[92];
};

struct LoginResult : public DataHeader
{
    LoginResult()
    {
        dataLength = sizeof(LoginResult);
        cmd = CMD_LOGIN_RESULT;
        result = 0;
    }
    char data[92];
    int result;
};

struct Logout :public DataHeader
{
    Logout()
    {
        dataLength = sizeof(Logout);
        cmd = CMD_LOGOUT;
    }
    char userName[32];
};

struct LogOutResult :public DataHeader
{
    LogOutResult()
    {
        dataLength = sizeof(LogOutResult);
        cmd = CMD_LOGOUT_RESULT;
        result = 0;
    }
    int result;
};

struct NewUserJoin :public DataHeader
{
    NewUserJoin()
    {
        dataLength = sizeof(NewUserJoin);
        cmd = CMD_NEW_USER_JOIN;
        sock = 0;
    }
    int sock;
};
#endif
View Code

此时,服务器只收客户端的消息,不回消息,1000个客户端,服务器可以每秒处理接近300万个数据包。

服务器和客户端简单的使用select网络模型(四)

 

上一篇:Socket网络编程,实现server/client


下一篇:开发设计模式(二) ActiveObject模式