使用C++创建UDP服务器,嵌入到跨平台的iOS和Android应用程序中 [英] Create UDP server using C++ to embed in cross platform iOS and Android app

查看:18
本文介绍了使用C++创建UDP服务器,嵌入到跨平台的iOS和Android应用程序中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一款跨平台的手游(iOS和Android),使用的是coCos2d-x。 我的大部分代码都是用C++编写的,而特定于操作系统的代码则使用了桥接在Objective-C/Java/Swift中。

我想知道是否有人在他们的应用中使用过C++库来托管UDP服务器?

编辑:到目前为止,我已经找到了很多特定于平台的解决方案(使用Java for Android,以及Cocoaasync for iOS等),但还没有专门用于跨平台应用程序的C++。

编辑:我更喜欢没有Boost的解决方案。最好包括一些简单的内容,如向项目中添加几个文件。

推荐答案

我最终得到的是:

h文件:

#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] = '';
            // 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只是一个简单的线程安全队列。

这篇关于使用C++创建UDP服务器,嵌入到跨平台的iOS和Android应用程序中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆