8_多平台移植

client移植到linux平台下

#define WIN32_LEAN_AND_MEAN   //windows.h和WinSock2.h有宏定义冲突,导致WinSock2.h必须要在windows.h前引用,定义该宏后可不用强制位置
#define _WINSOCK_DEPRECATED_NO_WARNINGS 
#define _CRT_SECURE_NO_WARNINGS

#ifdef _WIN32
    #include<windows.h>
    #include<WinSock2.h>
#else
    #include<unistd.h>
    #include<arpa/inet.h>
    #include<cstring>
    #define INVALID_SOCKET  (SOCKET)(~0)
    #define SOCKET_ERROR            (-1)
    #define SOCKET int
#endif
#include<iostream>
#include<thread>
#pragma comment(lib, "ws2_32.lib")  //method_1

enum CMD
{
    CMD_LOGIN,
    CMD_LOGIN_RESULT,
    CMD_LOGOUT,
    CMD_LOGOUT_RESULT,
    CMD_NEW_USER_JOIN,
    CMD_EXIT
};
struct DataHeader
{
    short data_length;
    short cmd;
};
struct Login : public DataHeader
{
    Login()
    {
        data_length = sizeof(Login);
        cmd = CMD_LOGIN;
    }
    char username[32];
    char password[32];
};
struct LoginResult : public DataHeader
{
    LoginResult()
    {
        data_length = sizeof(LoginResult);
        cmd = CMD_LOGIN_RESULT;
    }
    int result;
};
struct Logout : public DataHeader
{
    Logout()
    {
        data_length = sizeof(Logout);
        cmd = CMD_LOGOUT;
    }
    char username[32];
};
struct LogoutResult : public DataHeader
{
    LogoutResult()
    {
        data_length = sizeof(LogoutResult);
        cmd = CMD_LOGOUT_RESULT;
    }
    int result;
};
struct NewUserJOIN : public DataHeader
{
    NewUserJOIN()
    {
        data_length = sizeof(NewUserJOIN);
        cmd = CMD_NEW_USER_JOIN;
    }
    int sock;
};

bool judge_return_value(const char* function_name, int ret)
{
    if (SOCKET_ERROR == ret)
    {
        std::cout << function_name << "错误" << std::endl;
        return false;
    }
    return true;
}


bool return_value_error(const char* function_name, int ret)
{
    if (SOCKET_ERROR == ret)
    {
        std::cout << function_name << "错误" << std::endl;
        return true;
    }
    return false;
}

bool flag = true;
void cmdThread(SOCKET sock)
{
    char send_buf[128] = {};
    while (true)
    {
        //输入数据
        std::cin >> send_buf;
        if (strncmp(send_buf, "exit", sizeof("exit")) == 0)
        {
            DataHeader header = { 0, CMD_EXIT };
            int buf_len = send(sock, (char*)&header, sizeof(DataHeader), 0);
            flag = false;
            judge_return_value("send", buf_len);
            break;
        }
        else if (strncmp(send_buf, "login", sizeof("login")) == 0)
        {
            Login info = {};
            strcpy(info.username, "aaron");
            strcpy(info.password, "123456");
            int buf_len = send(sock, (char*)&info, sizeof(Login), 0);
            judge_return_value("send", buf_len);
            LoginResult res = {};
            buf_len = recv(sock, (char*)&res, sizeof(LoginResult), 0);
            judge_return_value("recv", buf_len);
            std::cout << "数据指令:" << res.cmd << ",数据长度:" << res.data_length << ",返回:" << res.result << std::endl;
        }
        else if (strncmp(send_buf, "logout", sizeof("logout")) == 0)
        {
            Logout info = {};
            strcpy(info.username, "aaron");
            int buf_len = send(sock, (char*)&info, sizeof(Logout), 0);
            judge_return_value("send", buf_len);
            LogoutResult res = {};
            buf_len = recv(sock, (char*)&res, sizeof(LoginResult), 0);
            judge_return_value("recv", buf_len);
            std::cout << "数据指令:" << res.cmd << ",数据长度:" << res.data_length << ",返回:" << res.result << std::endl;
        }
    }
}

int main()
{
#ifdef _WIN32
    WORD ver = MAKEWORD(2, 2);
    WSADATA dat;
    WSAStartup(ver, &dat);     //Windows socket网络环境的启动函数,需要引入ws2_32库文件,可以使用method_1,也可以在属性界面链接器的输入选项添加依赖项
#endif 
    //创建socket
    SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);    //客户端的地址由系统自动分配,不需要绑定
    //连接服务器
    sockaddr_in server_addr = {};
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(6666);
#ifdef _WIN32  
    server_addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
#else
    server_addr.sin_addr.s_addr = inet_addr("192.168.73.132");
#endif 
    int ret = connect(sock, (sockaddr*)&server_addr, sizeof(sockaddr_in));       //如果未发生错误,则返回零
    judge_return_value("connect", ret);
    //接受消息
    char buf[128] = {};
    int buf_len = recv(sock, buf, 128, 0);
    judge_return_value("recv", buf_len);
    std::cout << buf << std::endl;
    char recv_buf[128] = {};
    char send_buf[128] = {};
    std::thread t(cmdThread, sock);   //创建线程输入cmd
    t.detach();

    while (flag)
    {
        fd_set readfds;
        FD_ZERO(&readfds);
        FD_SET(sock, &readfds);

        timeval time = { 0, 0 };   //设置等待时间为0,即非阻塞模式
        int ret = select(sock + 1, &readfds, 0, 0, &time);
        if (FD_ISSET(sock, &readfds))
        {
            DataHeader header = {};
            int buf_len = recv(sock, (char*)&header, sizeof(DataHeader), 0);
            NewUserJOIN new_user = {};
            buf_len = recv(sock, (char *)&new_user + sizeof(DataHeader), sizeof(NewUserJOIN) - sizeof(DataHeader), 0);  //如果未发生错误, send 将返回发送的总字节数,该字节数可能小于 len 参数中请求发送的数量
            return_value_error("recv", buf_len);
            std::cout << "新客户:" << new_user.sock << "加入" << std::endl;
        }

    }
    std::cout << "连接退出" << std::endl;
    getchar();
    //关闭套接字
#ifdef _WIN32
    closesocket(sock);  
    WSACleanup();
#else
    close(sock);
#endif 
    return 0;
}

但是这样会导致主线程和cmd线程争抢服务器发来的包

server移植到linux平台下

#ifdef _WIN32
    #define WIN32_LEAN_AND_MEAN
    #define _WINSOCK_DEPRECATED_NO_WARNINGS
    #include<windows.h>
    #include<WinSock2.h>
    #pragma comment(lib,"ws2_32.lib")
#else
    #include<unistd.h> //uni std
    #include<arpa/inet.h>
    #include<string.h>

    #define SOCKET int
    #define INVALID_SOCKET  (SOCKET)(~0)
    #define SOCKET_ERROR            (-1)
#endif

#include<stdio.h>
#include<thread>
#include<vector>

#pragma comment(lib,"ws2_32.lib")

enum CMD
{
    CMD_LOGIN,
    CMD_LOGIN_RESULT,
    CMD_LOGOUT,
    CMD_LOGOUT_RESULT,
    CMD_NEW_USER_JOIN,
    CMD_ERROR
};

struct DataHeader
{
    short dataLength;
    short cmd;
};

//DataPackage
struct Login : public DataHeader
{
    Login()
    {
        dataLength = sizeof(Login);
        cmd = CMD_LOGIN;
    }
    char userName[32];
    char PassWord[32];
};

struct LoginResult : public DataHeader
{
    LoginResult()
    {
        dataLength = sizeof(LoginResult);
        cmd = CMD_LOGIN_RESULT;
        result = 0;
    }
    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;
        scok = 0;
    }
    int scok;
};

std::vector<SOCKET> g_clients;

int processor(SOCKET _cSock)
{
    //缓冲区
    char szRecv[4096] = {};
    // 5 接收客户端数据
    int nLen = (int)recv(_cSock, szRecv, sizeof(DataHeader), 0);
    DataHeader* header = (DataHeader*)szRecv;
    if (nLen <= 0)
    {
        printf("客户端<Socket=%d>已退出,任务结束。\n", _cSock);
        return -1;
    }
    switch (header->cmd)
    {
    case CMD_LOGIN:
    {
        recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
        Login* login = (Login*)szRecv;
        printf("收到客户端<Socket=%d>请求:CMD_LOGIN,数据长度:%d,userName=%s PassWord=%s\n", _cSock, login->dataLength, login->userName, login->PassWord);
        //忽略判断用户密码是否正确的过程
        LoginResult ret;
        send(_cSock, (char*)&ret, sizeof(LoginResult), 0);
    }
    break;
    case CMD_LOGOUT:
    {
        recv(_cSock, szRecv + sizeof(DataHeader), header->dataLength - sizeof(DataHeader), 0);
        Logout* logout = (Logout*)szRecv;
        printf("收到客户端<Socket=%d>请求:CMD_LOGOUT,数据长度:%d,userName=%s \n", _cSock, logout->dataLength, logout->userName);
        //忽略判断用户密码是否正确的过程
        LogoutResult ret;
        send(_cSock, (char*)&ret, sizeof(ret), 0);
    }
    break;
    default:
    {
        DataHeader header = { 0,CMD_ERROR };
        send(_cSock, (char*)&header, sizeof(header), 0);
    }
    break;
    }
    return 0;
}

int main()
{
#ifdef _WIN32
    //启动Windows socket 2.x环境
    WORD ver = MAKEWORD(2, 2);
    WSADATA dat;
    WSAStartup(ver, &dat);
    //------------
#endif
    //-- 用Socket API建立简易TCP服务端
    // 1 建立一个socket 套接字
    SOCKET _sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    // 2 bind 绑定用于接受客户端连接的网络端口
    sockaddr_in _sin = {};
    _sin.sin_family = AF_INET;
    _sin.sin_port = htons(4567);//host to net unsigned short
#ifdef _WIN32
    _sin.sin_addr.S_un.S_addr = INADDR_ANY;//inet_addr("127.0.0.1");
#else
    _sin.sin_addr.s_addr = INADDR_ANY;
#endif
    if (SOCKET_ERROR == bind(_sock, (sockaddr*)&_sin, sizeof(_sin)))
    {
        printf("错误,绑定网络端口失败...\n");
    }
    else {
        printf("绑定网络端口成功...\n");
    }
    // 3 listen 监听网络端口
    if (SOCKET_ERROR == listen(_sock, 5))
    {
        printf("错误,监听网络端口失败...\n");
    }
    else {
        printf("监听网络端口成功...\n");
    }

    while (true)
    {
        //伯克利套接字 BSD socket
        fd_set fdRead;//描述符(socket) 集合
        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 maxSock = _sock;
        for (int n = (int)g_clients.size() - 1; n >= 0; n--)
        {
            FD_SET(g_clients[n], &fdRead);
            if (maxSock < g_clients[n])
            {
                maxSock = g_clients[n];
            }
        }
        ///nfds 是一个整数值 是指fd_set集合中所有描述符(socket)的范围,而不是数量
        ///既是所有文件描述符最大值+1 在Windows中这个参数可以写0
        timeval t = { 1,0 };
        int ret = select(maxSock + 1, &fdRead, &fdWrite, &fdExp, &t);
        if (ret < 0)
        {
            printf("select任务结束。\n");
            break;
        }
        //判断描述符(socket)是否在集合中
        if (FD_ISSET(_sock, &fdRead))
        {
            FD_CLR(_sock, &fdRead);
            // 4 accept 等待接受客户端连接
            sockaddr_in clientAddr = {};
            int nAddrLen = sizeof(sockaddr_in);
            SOCKET _cSock = INVALID_SOCKET;
#ifdef _WIN32
            _cSock = accept(_sock, (sockaddr*)&clientAddr, &nAddrLen);
#else
            _cSock = accept(_sock, (sockaddr*)&clientAddr, (socklen_t *)&nAddrLen);
#endif
            if (INVALID_SOCKET == _cSock)
            {
                printf("错误,接受到无效客户端SOCKET...\n");
            }
            else
            {
                for (int n = (int)g_clients.size() - 1; n >= 0; n--)
                {
                    NewUserJoin userJoin;
                    send(g_clients[n], (const char*)&userJoin, sizeof(NewUserJoin), 0);
                }
                g_clients.push_back(_cSock);
                printf("新客户端加入:socket = %d,IP = %s \n", (int)_cSock, inet_ntoa(clientAddr.sin_addr));
            }
        }
        for (int n = (int)g_clients.size() - 1; n >= 0; n--)
        {
            if (FD_ISSET(g_clients[n], &fdRead))
            {
                if (-1 == processor(g_clients[n]))
                {
                    auto iter = g_clients.begin() + n;//std::vector<SOCKET>::iterator
                    if (iter != g_clients.end())
                    {
                        g_clients.erase(iter);
                    }
                }
            }
        }
        //printf("空闲时间处理其它业务..\n");
    }
#ifdef _WIN32
    for (int n = (int)g_clients.size() - 1; n >= 0; n--)
    {
        closesocket(g_clients[n]);
    }
    // 8 关闭套节字closesocket
    closesocket(_sock);
    //------------
    //清除Windows socket环境
    WSACleanup();
#else
    for (int n = (int)g_clients.size() - 1; n >= 0; n--)
    {
        close(g_clients[n]);
    }
    // 8 关闭套节字closesocket
    close(_sock);
#endif
    printf("已退出。\n");
    getchar();
    return 0;
}

Leave a Comment

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

Scroll to Top