使用C++创建UDP服务器以嵌入跨平台iOS和Android应用程序

3

我正在使用cocos2d-x开发iOS和Android平台的跨平台移动游戏。大部分代码采用C++编写,包含OS特定代码的部分则使用Objective-C / Java / Swift桥接。

请问是否有人使用过任何C++库在他们的应用中托管UDP服务器?

编辑:到目前为止,我找到了许多平台特定的解决方案(在Android中使用Java,在iOS中使用cocoaasync等),但尚未找到专门用于跨平台应用的C++解决方案。

编辑:我希望不使用boost来解决问题。最好是一些简单的文件,只需将它们添加到项目中即可。


1
我相信Boost(只需在Google上搜索,它是一个跨平台的C++库)有UDP和TCP套接字的版本。 - ALX23z
1
libuv是一个很好的选择。 - Hengqi Chen
3个回答

4

1
你可以使用 ASIO Standalone 库。它与 boost/asio 相同,但不需要其他 boost 库。我在类似的项目中(Android/iOS)使用了 boost/asio,它是迄今为止最优秀的解决方案。

1
这是我最终得到的内容:
#include "Queue.h"

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include <array>
#include <iostream>
#include <thread>

using namespace std;

#define MAXBUFFER_SIZE 1024

class UDPServer {
public:
    /**
     * Constructor
     *
     * @port the port on which the UDP server is listening for packets.
     */
    explicit UDPServer(unsigned short port);

    /**
     * Destructor
     */
    ~UDPServer() = default;

    /**
     * Setup the server.
     */
    void setupServer();

    /**
     * Get a single message.
     * For demonstration purposes, our messages is expected to be a array of int
     */
    bool getMessage(std::array<int, 4>& message);

    bool getIPAddress(std::array<int, 4>& message);

    void setFoundIP();

    bool isReady();

    void nextPort();

    int getPort();

private:
    bool _isBoundToPort = false;
    /**
     * The server port.
     */
    unsigned short port_;
    bool isFoundIP = false;
    /**
     * The thread-safe message queue.
     */
    Queue queue_;
    Queue _ipAddresses;
    /**
     * The UDP server function.
     */
    int UDPServerFunc();
};

cpp文件:

#include "UDPServer.h"

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>

using namespace std;

/**
 * This function parses an incoming message with the following format: 1;234;-89;-53;
 *
 * A valid message consists of 4 integer values separated by semicolons.
 */
inline std::array<int, 4> parseMessage(const std::string& input);
inline std::array<int,4> parseIp(const std::string& input);

UDPServer::UDPServer(unsigned short port)   {
    port_ = port;
}

bool UDPServer::getMessage(std::array<int, 4>& message) {
    return queue_.pop(message);
}

bool UDPServer::getIPAddress(std::array<int, 4>& message) {
    return _ipAddresses.pop(message);
}

void UDPServer::setFoundIP(){
    isFoundIP = true;
}

bool UDPServer::isReady(){
    return _isBoundToPort;
}

void UDPServer::nextPort(){
    port_++;
}

int UDPServer::getPort(){
    return port_;
}

void UDPServer::setupServer() {
    // Launch the server thread.
    std::thread t([this](){
        UDPServerFunc();
    });
    t.detach();
}

int UDPServer::UDPServerFunc() {

    // Creating socket file descriptor
    int sockfd;
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        perror("socket creation failed");
        exit(EXIT_FAILURE);
    }

    // Filling server information
    struct sockaddr_in servaddr, cliaddr;
    memset(&servaddr, 0, sizeof(servaddr));
    memset(&cliaddr, 0, sizeof(cliaddr));
    servaddr.sin_family = AF_INET; // IPv

    servaddr.sin_addr.s_addr = INADDR_ANY;
    servaddr.sin_port = htons(port_);

    // Bind the socket with the server address
    if (::bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }

    _isBoundToPort = true;
    while (true)  {
        // Read the next message from the socket.
        char message[MAXBUFFER_SIZE];
        socklen_t len = sizeof(struct sockaddr);
        ssize_t n = recvfrom(sockfd, (char *)&message, MAXBUFFER_SIZE, MSG_DONTWAIT,
                     (struct sockaddr *)&cliaddr, (socklen_t*)&len);
        if (n > 0) {
            message[n] = '\0';
            // Parse incoming data and push the result on the queue.
            // Parsed messages are represented as a std::array<int, 4>.

            if(!isFoundIP){
                _ipAddresses.push(parseIp(message));
            }else{
                queue_.push(parseMessage(message));
            }
        } else {
            // Wait a fraction of a millisecond for the next message.
            usleep(100);
        }
    }

    return 0;
}

我从我的答案中删除了任何不必要的代码,因为真正重要的只是上面的代码。如果有人需要多余的函数,我在Github上分享了代码,并且稍后还会添加一些示例。
上面的代码非常简单,具有用于提取IP地址或由分号分隔的四个数字集的几个解析函数。上面的代码足够简单,可以根据自己的定制消息进行修改。
Queue.h只是一个简单的线程安全队列。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接