ZBLOG

spdk使用spdk_sock_listen_ext的代码

以下是使用 spdk_sock_listen_ext() 函数监听地址的示例代码:

#include <stdio.h>
#include <stdlib.h>

#include <rte_config.h>
#include <rte_eal.h>
#include <rte_lcore.h>

#include "spdk/env.h"
#include "spdk/thread.h"
#include "spdk/sock.h"

#define PORTNUM 4420

static void
handle_sock(struct spdk_sock *sock)
{
    char buf[512];
    ssize_t bytes_read;

    while (1) {
        bytes_read = spdk_sock_recv(sock, buf, sizeof(buf));
        if (bytes_read <= 0) {
            printf("error: recv() returned %zd\n", bytes_read);
            break;
        }

        printf("received %zd bytes: %.*s\n", bytes_read, (int)bytes_read, buf);

        if (spdk_sock_send(sock, buf, bytes_read) != bytes_read) {
            printf("error: failed to send echo response on socket %d\n",
                   spdk_sock_get_fd(sock));
            break;
        }
    }
}

static int
listener_thread(void *arg)
{
    struct spdk_sock *listener;
    struct spdk_sock_opts opts = {};
    const uint32_t max_unhandled_bytes = 1024;

    /* Listen on IPv4 and IPv6 */
    listener = spdk_sock_listen_ext(PORTNUM, true /* ipv6 */, &opts,
                                    max_unhandled_bytes);
    if (!listener) {
        fprintf(stderr, "Failed to listen on port %d\n", PORTNUM);
        return 1;
    }

    while (true) {
        struct spdk_sock *sock;

        sock = spdk_sock_accept(listener);
        if (!sock) {
            continue;
        }

        handle_sock(sock);

        /* Destroy the socket when the client disconnects. */
        spdk_sock_close(sock);
    }

    return 0;
}

int
main(int argc, char **argv)
{
    int rc;

    rc = rte_eal_init(argc, argv);
    if (rc < 0) {
        return -1;
    }

    /* Initialize DPDK environment */
    rc = spdk_env_init(NULL);
    if (rc < 0) {
        fprintf(stderr, "Unable to initialize SPDK env\n");
        return 1;
    }

    /* Start a new thread for listening on the specified address and port number */
    spdk_thread_create(NULL, listener_thread, NULL);

    /* Wait for all threads to complete before exiting. */
    spdk_app_fini();
}

此示例代码启动了一个 SPDK 应用程序,该应用程序在 PORTNUM 端口上侦听 IPv4 和 IPv6 地址,并在接收到客户端连接时使用 handle_sock() 函数处理客户端请求。每当有新的客户端连接时,就会创建一个新的线程来处理该客户端。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://sdn.0voice.com/?id=1565

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?