使用nghttp2实现IOS 的 APNS的推送测试例子

基于nghttp2的apns HTTP2 C++ 测试程序 http2 nghttp2 apns openssl 测试程序, 版权所有! 不得转载! /* * nghttp2 - HTTP/2 C Library */ #ifdef HAVE_CONFIG_H #include #endif /* HAVE_CONFIG_H */ #include #include #ifdef HAVE_UNISTD_H #include #endif 阅读详情

能用代码就不废话

调用例子和代码

//调用示例:
int main(int argc , char**argv)
{
     testapns( "/path/to/your/ca",
              "/path/yourkey_cert.pem",
            "/path/yourkey_cert.pem",
              "api.push.apple.com",
              "/3/device/DB10092BAF5385B9AD58AB696DC7E8ECC6061F04AFD79E1387EB38D0E3712DCB",
              "alert",
             "com.company.game",
            "10",
            "0",
           "{ \"aps\" : { \"alert\" : \"Hello\" } }"
                                     
             );

      return 0;
}

#ifdef HAVE_CONFIG_H
#  include <config.h>
#endif /* HAVE_CONFIG_H */

#include <inttypes.h>
#include <stdlib.h>

# include <fcntl.h>

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

#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <errno.h>

#include <nghttp2/nghttp2.h>

#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/conf.h>
  #include <unistd.h>

#include <string>

#include <iostream>


struct Connection {
  SSL *ssl;
  nghttp2_session *session;
  /* WANT_READ if SSL/TLS connection needs more input; or WANT_WRITE
     if it needs more output; or IO_NONE. This is necessary because
     SSL/TLS re-negotiation is possible at any time. nghttp2 API
     offers similar functions like nghttp2_session_want_read() and
     nghttp2_session_want_write() but they do not take into account
     SSL/TSL connection. */
  int want_io;
};


struct XRequest {
    const char *host;
    /* In this program, path contains query component as well. */
    const  char *path;
    /* This is the concatenation of host and port with ":" inbetween. */
    const  char *hostport;
    /* Stream ID for this request. */
    int32_t stream_id;
    uint16_t port;
    
    const char *pdata;
    const char *topic;
    const char *pushtype;
    const char *priority;
    const char *expiration;
    size_t nleft;
    size_t nsize;
};



enum { IO_NONE, WANT_READ, WANT_WRITE };



int get_cert_password_cb2(char *buf,int size, int rwflag, void *userdata)
{

    std::string password="123456";
    //g_pConfigData->GetStr(CONF_KX_CERT_PASS, &password);
   // Capns_client::log->debug("desc=get_cert_password password=%s\n",password.c_str());

    strcpy(buf,password.c_str());

    return password.length();
}


static void die(const char *msg) {
  fprintf(stderr, "FATAL: %s\n", msg);
  exit(EXIT_FAILURE);
}

/*
 * Prints error containing the function name |func| and error code
 * |error_code| and exit.
 */
static void diec(const char *func, int error_code) {
  fprintf(stderr, "FATAL: %s: error_code=%d, msg=%s\n", func, error_code,
          nghttp2_strerror(error_code));
  exit(EXIT_FAILURE);
}


static void dief(const char *func, const char *msg) {
  fprintf(stderr, "FATAL: %s: %s\n", func, msg);
  exit(EXIT_FAILURE);
}

/*
 * The implementation of nghttp2_send_callback type. Here we write
 * |data| with size |length| to the network and return the number of
 * bytes actually written. See the documentation of
 * nghttp2_send_callback for the details.
 */
static ssize_t send_callback(nghttp2_session *session, const uint8_t *data,
                             size_t length, int flags, void *user_data) {
  struct Connection *connection;
  int rv;
  (void)session;
  (void)flags;

  connection = (struct Connection *)user_data;
  //connection->want_io = IO_NONE;
  ERR_clear_error();
  rv = SSL_write(connection->ssl, data, (int)length);
  if (rv <= 0) {
    int err = SSL_get_error(connection->ssl, rv);
    if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
      connection->want_io =
          (err == SSL_ERROR_WANT_READ ? WANT_READ : WANT_WRITE);
      rv = NGHTTP2_ERR_WOULDBLOCK;
    } else {
      rv = NGHTTP2_ERR_CALLBACK_FAILURE;
    }
  }
  return rv;
}

/*
 * The implementation of nghttp2_recv_callback type. Here we read data
 * from the network and write them in |buf|. The capacity of |buf| is
 * |length| bytes. Returns the number of bytes stored in |buf|. See
 * the documentation of nghttp2_recv_callback for the details.
 */
static ssize_t recv_callback(nghttp2_session *session, uint8_t *buf,
                             size_t length, int flags, void *user_data) {
  struct Connection *connection;
  int rv;
  (void)session;
  (void)flags;

  connection = (struct Connection *)user_data;
  connection->want_io = IO_NONE;
  ERR_clear_error();
  rv = SSL_read(connection->ssl, buf, (int)length);
  if (rv < 0) {
    int err = SSL_get_error(connection->ssl, rv);
    if (err == SSL_ERROR_WANT_WRITE || err == SSL_ERROR_WANT_READ) {
      connection->want_io =
          (err == SSL_ERROR_WANT_READ ? WANT_READ : WANT_WRITE);
      rv = NGHTTP2_ERR_WOULDBLOCK;
    } else {
      rv = NGHTTP2_ERR_CALLBACK_FAILURE;
    }
  } else if (rv == 0) {
    rv = NGHTTP2_ERR_EOF;
  }
  return rv;
}

static int on_frame_send_callback(nghttp2_session *session,
                                  const nghttp2_frame *frame, void *user_data) {
  size_t i;
  (void)user_data;

  switch (frame->hd.type) {
  case NGHTTP2_HEADERS:
    if (nghttp2_session_get_stream_user_data(session, frame->hd.stream_id)) {
      const nghttp2_nv *nva = frame->headers.nva;
      printf("[INFO] C ----------------------------> S (HEADERS)\n");
      for (i = 0; i < frame->headers.nvlen; ++i) {
        fwrite(nva[i].name, 1, nva[i].namelen, stdout);
        printf(": ");
        fwrite(nva[i].value, 1, nva[i].valuelen, stdout);
        printf("\n");
      }
    }
    break;
  case NGHTTP2_RST_STREAM:
    printf("[INFO] C ----------------------------> S (RST_STREAM)\n");
    break;
  case NGHTTP2_GOAWAY:
    printf("[INFO] C ----------------------------> S (GOAWAY)\n");
    break;
  }
  return 0;
}

static int on_frame_recv_callback(nghttp2_session *session,
                                  const nghttp2_frame *frame, void *user_data) {
  size_t i;
  (void)user_data;

  switch (frame->hd.type) {
  case NGHTTP2_HEADERS:
    if (frame->headers.cat == NGHTTP2_HCAT_RESPONSE) {
      const nghttp2_nv *nva = frame->headers.nva;
      struct XRequest *req;
      req = (struct XRequest *)nghttp2_session_get_stream_user_data(session, frame->hd.stream_id);
      if (req) {
        printf("[INFO] C <---------------------------- S (HEADERS)\n");
        for (i = 0; i < frame->headers.nvlen; ++i) {
          fwrite(nva[i].name, 1, nva[i].namelen, stdout);
          printf(": ");
          fwrite(nva[i].value, 1, nva[i].valuelen, stdout);
          printf("\n");
        }
      }
    }
    break;
  case NGHTTP2_RST_STREAM:
    printf("[INFO] C <---------------------------- S (RST_STREAM)\n");
    break;
  case NGHTTP2_GOAWAY:
    printf("[INFO] C <---------------------------- S (GOAWAY)\n");
    break;
  }
  return 0;
}

/*
 * The implementation of nghttp2_on_stream_close_callback type. We use
 * this function to know the response is fully received. Since we just
 * fetch 1 resource in this program, after reception of the response,
 * we submit GOAWAY and close the session.
 */
static int on_stream_close_callback(nghttp2_session *session, int32_t stream_id,
                                    uint32_t error_code, void *user_data) {
  struct XRequest *req;
  (void)error_code;
  (void)user_data;

  req =  (struct XRequest *)nghttp2_session_get_stream_user_data(session, stream_id);
  if (req) {
    int rv;
    rv = nghttp2_session_terminate_session(session, NGHTTP2_NO_ERROR);

    if (rv != 0) {
      diec("nghttp2_session_terminate_session", rv);
    }
  }
  return 0;
}

/*
 * The implementation of nghttp2_on_data_chunk_recv_callback type. We
 * use this function to print the received response body.
 */
static int on_data_chunk_recv_callback(nghttp2_session *session, uint8_t flags,
                                       int32_t stream_id, const uint8_t *data,
                                       size_t len, void *user_data) {
  struct XRequest *req;
  (void)flags;
  (void)user_data;

  req =  (struct XRequest *)nghttp2_session_get_stream_user_data(session, stream_id);
  if (req) {
    printf("[INFO] C <---------------------------- S (DATA chunk)\n"
           "%lu bytes\n",
           (unsigned long int)len);
    fwrite(data, 1, len, stdout);
    printf("\n");
  }
  return 0;
}

#define MAKE_NV(NAME, VALUE)                                                   \
  {                                                                            \
    (uint8_t *)NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, sizeof(VALUE) - 1,    \
        NGHTTP2_NV_FLAG_NONE                                                   \
  }

#define MAKE_NV_CS(NAME, VALUE)                                                \
  {                                                                            \
    (uint8_t *)NAME, (uint8_t *)VALUE, sizeof(NAME) - 1, strlen(VALUE),        \
        NGHTTP2_NV_FLAG_NONE                                                   \
  }


ssize_t nghttp2_prd_callback(
nghttp2_session *session, int32_t stream_id, uint8_t *buf, size_t length,
uint32_t *data_flags, nghttp2_data_source *source, void *user_data)
{
    struct XRequest *req = (struct XRequest *)source->ptr;
    
      size_t n = std::min(req->nleft, length);
      memcpy(buf,req->pdata+ req->nsize - req->nleft, n);
      req->nleft -= n;
      if (req->nleft == 0) {
        *data_flags |= NGHTTP2_DATA_FLAG_EOF;
      }
      return n;
}


/*
 * Update |pollfd| based on the state of |connection|.
 */
static void ctl_poll(struct pollfd *pollfd, struct Connection *connection) {
  pollfd->events = 0;
  if (nghttp2_session_want_read(connection->session) ||
      connection->want_io == WANT_READ) {
    pollfd->events |= POLLIN;
  }
  if (nghttp2_session_want_write(connection->session) ||
      connection->want_io == WANT_WRITE) {
    pollfd->events |= POLLOUT;
  }
}



/*
 * Submits the request |req| to the connection |connection|.  This
 * function does not send packets; just append the request to the
 * internal queue in |connection->session|.
 */
static void submit_request(struct Connection *connection, struct XRequest *req) {
  int32_t stream_id;
  /* Make sure that the last item is NULL */
  const nghttp2_nv nva[] = {MAKE_NV(":method", "POST"),
                            MAKE_NV_CS(":path", req->path),
                            MAKE_NV(":scheme", "https"),
                            MAKE_NV_CS(":authority", req->hostport),
                            MAKE_NV("accept", "*/*"),
                            MAKE_NV("user-agent", "nghttp2/" NGHTTP2_VERSION),
              MAKE_NV_CS("apns-topic",req->topic),
              MAKE_NV_CS("apns-priority",req->priority),
              MAKE_NV_CS("apns-expiration",req->expiration),
              MAKE_NV_CS("apns-push-type",req->pushtype),
              MAKE_NV_CS("host",req->host)
      
  };
    
    nghttp2_data_provider *prd = new nghttp2_data_provider();
    prd->source.ptr = req;
    
    prd->read_callback =nghttp2_prd_callback;
    stream_id = nghttp2_submit_request(connection->session, NULL, nva,
                                     sizeof(nva) / sizeof(nva[0]), prd, req);

  if (stream_id < 0) {
    diec("nghttp2_submit_request", stream_id);
  }

  req->stream_id = stream_id;
  printf("[INFO] Stream ID = %d\n", stream_id);
}


static void make_non_block(int fd) {
  int flags, rv;
  while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR)
    ;
  if (flags == -1) {
    dief("fcntl", strerror(errno));
  }
  while ((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR)
    ;
  if (rv == -1) {
    dief("fcntl", strerror(errno));
  }
}

static void set_tcp_nodelay(int fd) {
  int val = 1;
  int rv;
  rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, (socklen_t)sizeof(val));
  if (rv == -1) {
    dief("setsockopt", strerror(errno));
  }
}



/*
 * Performs the network I/O.
 */
static void exec_io(struct Connection *connection) {
  int rv;
  rv = nghttp2_session_recv(connection->session);
  if (rv != 0) {
    diec("nghttp2_session_recv", rv);
  }
  rv = nghttp2_session_send(connection->session);
  if (rv != 0) {
    diec("nghttp2_session_send", rv);
  }
}


int testapns( const std::string &m_capath,
              const std::string &m_cerfile,
              const std::string &m_keyfile,
              const std::string &m_host,
              const std::string &urlpath,
              const std::string &pushtype,
             const std::string &topic,
             const std::string &priority,
             const std::string &expiration,
            const std::string &data
                                     
             )
{
    nfds_t npollfds = 1;
    struct pollfd pollfds[1];

    struct sockaddr_in   m_server_addr;
    struct hostent       m_host_info;

    int m_port;

    int err;
    int ret=0;
    struct timeval tv;
    time_t now=time(NULL);
    #define ERR_STRING_LEN  256
    char errString[ERR_STRING_LEN]={0};
    #define GET_SSL_ERR_STRING  \
    ERR_error_string_n(ERR_get_error(),errString,ERR_STRING_LEN-1)

    int hostbuf_len=1024;
    char *hostbuf=NULL;
    bool retry=false;

    /* Create an SSL_METHOD structure (choose an SSL/TLS protocol version) */
    const SSL_METHOD * m_method = SSLv23_method();
    if(!m_method)
    {
        return -1;
    }


    /* Create an SSL_CTX structure */
    SSL_CTX *  m_ctx = SSL_CTX_new(m_method);
    if(!m_ctx)
    {
        return -1;
    }

    SSL_CTX_set_default_passwd_cb(m_ctx,get_cert_password_cb2);


    /* Load the CA from the Path */
    if(SSL_CTX_load_verify_locations(m_ctx, NULL, m_capath.c_str()) <= 0)
    {
     GET_SSL_ERR_STRING  ;
     std::cout << "err=failed_to_set_ca ssl_err= " << errString << "\n";
     return -1;
    }

    /* Load the client certificate into the SSL_CTX structure */
    if (SSL_CTX_use_certificate_file(m_ctx, m_cerfile.c_str(), SSL_FILETYPE_PEM) <= 0) {
        GET_SSL_ERR_STRING  ;
        std::cout << "SSL_CTX_use_certificate_filessl_err= " << errString << "\n";
        return -1;
    }

    /* Load the private-key corresponding to the client certificate */
    if (SSL_CTX_use_PrivateKey_file(m_ctx, m_keyfile.c_str(), SSL_FILETYPE_PEM) <= 0) {
     GET_SSL_ERR_STRING  ;
     std::cout << "SSL_CTX_use_PrivateKey_file = " << errString << "\n";
     return -1;
    }

    /* Check if the client certificate and private-key matches */
    if (!SSL_CTX_check_private_key(m_ctx)) {
      GET_SSL_ERR_STRING  ;
       std::cout << "SSL_CTX_check_private_key = " << errString << "\n";
       return -1;
    }

    /* Set up a TCP socket */
    int m_sock = socket (PF_INET, SOCK_STREAM, IPPROTO_TCP);
    if(m_sock == -1)
    {
        err=-1;
        return -1;
    }

    memset (&m_server_addr, '\0', sizeof(m_server_addr));
    m_server_addr.sin_family      = AF_INET;
    m_server_addr.sin_port        = htons(m_port);       /* Server Port number */

    if((hostbuf=(char *)malloc(hostbuf_len))==NULL)
    {
        return -1;
    }

    struct hostent  *phost=NULL;
    int ret1=0;
    phost = gethostbyname(m_host.c_str());

    m_server_addr.sin_addr = *(struct in_addr*)phost->h_addr_list[0];
    char m_connect_ip[30];
     inet_ntop(AF_INET, &m_server_addr.sin_addr, m_connect_ip,sizeof(m_connect_ip));
           m_connect_ip[15]='\0';
    m_server_addr.sin_port = htons(443);
    printf("host ip %s \n", m_connect_ip);


    /* Establish a TCP/IP connection to the SSL client */
    err = ::connect(m_sock, (struct sockaddr*) &m_server_addr, sizeof(m_server_addr));
    if(err == -1)
    {
        return -1;
    }


    /* An SSL structure is created */
    SSL *m_ssl = SSL_new(m_ctx);
    if(!m_ssl)
    {
        err=-1;
        return -1;
    }

    /* Assign the socket into the SSL structure (SSL and socket without BIO) */
    SSL_set_fd(m_ssl, m_sock);

    /* Perform SSL Handshake on the SSL client */
    err = SSL_connect(m_ssl);
    if(err <= 0)
    {
        GET_SSL_ERR_STRING  ;
        err=-1;
        return -1;
    }

    struct Connection connection;
    connection.ssl = m_ssl;
    nghttp2_session_callbacks *callbacks;
    int rv = nghttp2_session_callbacks_new(&callbacks);

    nghttp2_session_callbacks_set_send_callback(callbacks, send_callback);

     nghttp2_session_callbacks_set_recv_callback(callbacks, recv_callback);

     nghttp2_session_callbacks_set_on_frame_send_callback(callbacks,
                                                          on_frame_send_callback);

     nghttp2_session_callbacks_set_on_frame_recv_callback(callbacks,
                                                          on_frame_recv_callback);

     nghttp2_session_callbacks_set_on_stream_close_callback(
         callbacks, on_stream_close_callback);

     nghttp2_session_callbacks_set_on_data_chunk_recv_callback(
         callbacks, on_data_chunk_recv_callback);



    rv = nghttp2_session_client_new(&connection.session, callbacks, &connection);

    nghttp2_session_callbacks_del(callbacks);

    if (rv != 0) {
      diec("nghttp2_session_client_new", rv);
    }

    rv = nghttp2_submit_settings(connection.session, NGHTTP2_FLAG_NONE, NULL, 0);


    connection.want_io = IO_NONE;

     /* Here make file descriptor non-block */
    make_non_block(m_sock);
    set_tcp_nodelay(m_sock);

    if (rv != 0) {
      diec("nghttp2_submit_settings", rv);
    }
    struct XRequest req;
    req.host = m_host.c_str();
    req.path = urlpath.c_str();
    req.hostport = m_host.c_str();
    req.pdata = data.c_str();
    req.nsize = req.nleft = strlen(req.pdata);
    req.expiration = expiration.c_str();
    req.priority = priority.c_str();
    req.pushtype = pushtype.c_str();
    req.topic = topic.c_str();
    /* Submit the HTTP request to the outbound queue. */
    submit_request(&connection, &req);


    pollfds[0].fd = m_sock;
    ctl_poll(pollfds, &connection);

    /* Event loop */
    while (nghttp2_session_want_read(connection.session) ||
         nghttp2_session_want_write(connection.session)) {
    int nfds = poll(pollfds, npollfds, -1);
    if (nfds == -1) {
      dief("poll", strerror(errno));
    }
    if (pollfds[0].revents & (POLLIN | POLLOUT)) {
      exec_io(&connection);
    }
    if ((pollfds[0].revents & POLLHUP) || (pollfds[0].revents & POLLERR)) {
      die("Connection error");
    }
    ctl_poll(pollfds, &connection);
    }

    nghttp2_session_del(connection.session);
    SSL_shutdown(m_ssl);
    SSL_free(m_ssl);
    SSL_CTX_free(m_ctx);
    shutdown(m_sock, SHUT_WR);
    close(m_sock);
    
    return 0;

}

 

【APNS】使用apns auth key测试推送, BadDeviceToken 错误问题排查 原因:setBatteryMonitoringEnabled: crash问题解决 (setBatteryMonitoringEnabled: are not thread-safe);要保证每次对batteryLevelDidChange 阅读详情

相关推荐

走马观碑组智能车竞赛:目标板识别算法优化与实战技巧(基于OpenCV)

本文针对智能车竞赛走马观碑组别的核心挑战,深入探讨了基于OpenCV的目标板识别算法优化与实战技巧。文章系统分析了PVC赛道环境下的光照、运动模糊等干扰因素,详细拆解了从红色矩形定位、透视校正到特征提取与分类的完整流程,并提供了工程优化、速度提升及现场调试的实用策略,旨在帮助参赛队伍构建一套在高速运动中既准又快的鲁棒识别系统。

life6的博客 732

nghttp2 中的常用API

nghttp2_session_callbacks_new int nghttp2_session_callbacks_new(nghttp2_session_callbacks* *callbacks_ptr) 当初始化多个 nghttp2_session对象, 可以使用初始化的对象,当应用程序使用这个对象完成时,可以使用 nghttp2_session_callbacks_del可以释放

程序手艺人 - 嵌入式音频技术之旅 5021

Win11安装Office2021

windows11安装office2021。

1万+

在linux上使用c++实现http/2协议进行通信

采用nghttp2是一个http/2协议的翻译器。 采用openssl进行TLS通信,实现加密和安全。 采用socket与目标server建立tcp连接,实现底层数据通信。         nghttp2 是一个很优秀的 HTTP/2 的 C 类实现。它的前身是 SPDY 库 spdylay,作者都是 Tatsuhiro Tsujikawa. 地址:https://github.com

天道酬勤 6615

BambuStudio学习笔记:GCode 类

关键成员解析 核心配置组件 状态跟踪系统 功能模块集成 核心方法剖析 主输出管道 实现多阶段处理: 分层处理流程: 实现智能路径规划: 关键特性: 实现模板故障检测: 采用三级流水线: 支持扩展类型: 实现多通道输出: 采用: 实现: 支持: 支持模块化编译: 典型流程: 实现功能:

zzzkk2009的专栏 927

Allegro File菜单实战指南:从导入网表到导出BOM的完整流程

PCB设计离不开对EDA软件菜单体系的深入理解。在Cadence Allegro中,File菜单是数据流转的中枢,它不仅是新建、打开、保存的基础入口,更是连接原理图与版图、设计与制造的关键桥梁。工程师常遇到的“导入网表报错”“导出BOM为空”“板框不闭合”等高频问题,大多源于对File菜单中Import与Export功能的理解不到位。从基础概念出发,先厘清Import(网表、DXF、IPC)与Export(BOM、ODB++、DXF)的工作原理,再结合版本兼容、封装库路径、单位设置等工程细节,即可构建完整的

weixin_32950759的博客 295

深入理解HTTP/2:nghttp2库源码解析及客户端实现示例

本文结合nghttp2库源码,详细剖析了HTTP/2的主要特性实现,如二进制帧、多路复用、头部压缩和服务器推送。同时,通过一个C语言示例代码,演示了如何使用nghttp2库创建一个HTTP/2客户端,实现发送GET请求、打印响应、错误处理、超时、取消请求和流量控制等功能。

陆业聪 2827

DVWA全级别详细通关教程

dvwa全级别详细通关教程,暴力破解,命令注入,CSRF跨站请求伪造,文件包含,文件上传​,SQL注入,XSS

m0_62063669的博客 1万+

nghttp2开发者指南:深入理解HTTP/2协议栈实现

nghttp2库最显著的设计特点是不直接处理任何I/O操作。这个设计决策使得库能够专注于HTTP/2协议的核心功能,同时为开发者提供了最大的灵活性。 ### 无I/O设计的优势 1. **易于集成**:不强制使用特定的I/O模型,可以轻松嵌入到现有的事件循环系统中 2. **语言绑定友好**:简化了与其他编程语言的绑定实现 3. **协议专注**:专注于HTTP/2协议处理,不涉及传输层细节 ...

gitblog_00942的博客 634

华为OD机考双机位C卷 - AI处理器组合 (Java & Python & JS & GO & C++ & C)

> 2026华为OD机试双机位C卷 - 华为OD上机考试双机位C卷 华为OD机试双机位C卷真题目录点击查看: [【全网首发】2026华为OD机位C卷 机考真题题库含考点说明以及在线OJ(OD上机考试双机位C卷)](https://blog.youkuaiyun.com/banxia_frontend/article/details/155503868)

算法大师! 233

python:实现brutefore破解wifi(附完整源码)

python:实现brutefore破解wifi(附完整源码)

希望我的博客,能帮上你解决学习中工作中所遇到的问题 5706

快速上手nghttp2:HTTP/2客户端使用指南

🚀 想要体验HTTP/2协议带来的性能提升吗?nghttp2作为一款功能强大的HTTP/2客户端,能够帮助你轻松测试和调试HTTP/2服务。本文将带你快速掌握nghttp2的核心用法,让你的网络开发更高效! ## 什么是nghttp2? nghttp2是一个HTTP/2 C语言库和命令行工具,实现了完整的HTTP/2协议栈。它不仅提供了libnghttp2开发库,还包含了实用的命令行客户端,

gitblog_01099的博客 748

控制科学与工程(自动化)保研经验【4】——浙大篇

控制科学与工程(自动化)保研经验【4】——浙大篇

Control Everything 1万+

Python与Keras文本分类实战:从TF-IDF到CNN的完整指南

文本分类是自然语言处理(NLP)中的基础任务,其核心原理是将非结构化的文本数据转化为机器可处理的数值特征,进而实现自动化的内容理解和归类。传统方法如TF-IDF通过统计词频与文档频率来衡量词语重要性,为逻辑回归等模型提供有效的特征表示。随着深度学习的发展,词嵌入技术通过低维稠密向量捕捉词语间的语义关联,显著提升了模型对语言的理解能力。卷积神经网络(CNN)则能自动提取文本中的局部短语模式,在多尺寸卷积核的协同作用下,实现对复杂语言结构的有效建模。这些技术在情感分析、内容审核、新闻分类等场景中具有广泛应用价值

weixin_30564785的博客 508

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

iOS HTTP 2 Server Push 探索

本文首发地址为-iOS HTTP/2 Server Push 探索 | 李剑飞的博客 HTTP/2 Server Push 是什么 当用户的浏览器和服务器在建立链接后,服务器主动将一些资源推送给浏览器并缓存起来,这样当浏览器接下来请求这些资源时就直接从缓存中读取,不会在从服务器上拉了,提升了速率。举一个例子就是: 假如一个页面有3个资源文件index.html,index.css,index....

weixin_33816611的博客 134

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

小智音箱通过HTTP/2高效交互服务器数据

本文深入解析小智音箱如何利用HTTP/2的多路复用、二进制分帧、头部压缩和流优先级等特性,优化云-端通信效率,显著降低延迟、节省带宽并提升用户体验。

weixin_35973118的博客 395

SAP B1中文培訓教材_SDK

公司内部培训资料,对开发工具 ,DIAPI, UIAPI,Add-ON有详细解说

nghttp2库源码解析及客户端实现

nghttp2 是一个用 C 语言编写的高性能 HTTP/2 库,提供了客户端、服务器和代理的实现。libnghttp2:核心库,实现了 HTTP/2 协议。nghttpx:基于 nghttp2 的高性能代理。nghttp:命令行客户端工具。

ghie9090的博客 706

libhv/libhv HTTP/2支持:新一代Web协议实现

在现代Web应用开发中,HTTP/2协议已成为提升性能的关键技术。相比HTTP/1.x,HTTP/2通过多路复用、头部压缩和服务器推送等特性,显著降低了网络延迟并提高了吞吐量。本文将深入剖析libhv/libhv项目中HTTP/2协议的实现细节,从核心架构到实际应用,全面展示这一高性能网络库如何应对新一代Web协议的挑战。 ## HTTP/2协议核心原理 HTTP/2(超文本传输协议第2版)是...

gitblog_00286的博客 513

nghttp2 项目教程

nghttp2 项目的目录结构如下: ``` nghttp2/ ├── AUTHORS ├── CMakeLists.txt ├── CMakeOptions.txt ├── CONTRIBUTION ├── COPYING ├── ChangeLog ├── Dockerfile ├── LICENSE ├── Makefile.am ├── NEWS ├── README ├── READM...

gitblog_00518的博客 494

nghttp2客户端使用教程:全面掌握HTTP/2请求处理

nghttp2是一个功能强大的HTTP/2 C语言库和工具集,为开发者提供了完整的HTTP/2协议实现。无论你是想要构建高性能的HTTP/2客户端,还是需要对HTTP/2协议进行深度调试,nghttp2都能满足你的需求。🚀 ## 什么是nghttp2? nghttp2是一个开源的HTTP/2实现,它提供了完整的C语言库以及实用的命令行工具。该库实现了HTTP/2帧层、HPACK头部压缩等核心

gitblog_00534的博客 1156

封装ng2的Http请求

需求描述:http请求的url格式都是’http://debug.xxx.com‘+’/url’,在请求之前显示loading,在请求结束隐藏loading 目前只封装了get,其他请求类似,后期再补充MyHttp.tsimport {Injectable} from '@angular/core'; import {Http} from '@angular/http'; import 'rxjs

Pluto 3463

Nghttp2之nghttpx

nghttpx 相关配置 user=root workers=1 http2-proxy=yes dns-server=8.8.8.8 # https configure certificate-file=/path/to/cert.cert private-key-file=/path/to/cert.key #https configure frontend=10.0.0.100,443;...

浴血重生-学习空间 2070

基于nghttp2的APNs new API 测试(c实现)

主要为了测试api的一些特性 3.2 :   发现不用带有content-length 字段也可以发送,但文档中说的是 must provide,待进一步确认 3.22:   做了个工具,推单条的   APNs推送的测试工具(使用新的HTTP2 api)    ----- via github: https://github.com/wardenlym/apns2-d...

weixin_30413739的博客 1627
上一篇: 如何解开和反编译思科cisco的交换机固件
下一篇: Wacom 数位板 和冠 手绘笔 Photoshop MacOS 延时卡顿丢笔解决办法
aerror
博客等级 码龄23年 392粉丝 193原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值