示例记录

#include "lwip_test.h"#include "lwip/sockets.h"#include "netdev.h"#define DBG_ENABLE#define DBG_TAG "lwip.tst"#define DBG_LVL DBG_LOG#include #define SERVER_PORT 8080#define SERVER_HOST "192.168.199.194"#define REC_BUF_LEN 512#if 1static rt_thread_t mq_rec;static struct netdev *netdev = RT_NULL;const char *msg = "hello sever,i is client";static void _th_entity(void *args) {struct sockaddr_in client_addr;struct sockaddr_in server_addr;int sockfd = -1;int result;/* 通过名称获取 netdev 网卡对象 */netdev = netdev_get_by_name(ETH_DEV_NAME);if (netdev == RT_NULL) {LOG_E("get network interface device(%s) failed.", ETH_DEV_NAME);return;}while (netdev->ip_addr.addr == 0 || netdev->gw.addr == 0) {LOG_W("current netdev stat is :%d.", netdev->flags);rt_thread_mdelay(1000);}LOG_I("current netdev ip addr :%s.", inet_ntoa(netdev->ip_addr));/* 初始化需要绑定的客户端地址 */client_addr.sin_family = AF_INET;client_addr.sin_port = htons(8080);client_addr.sin_addr.s_addr = netdev->ip_addr.addr;rt_memset(&(client_addr.sin_zero), 0, sizeof(client_addr.sin_zero));/* 初始化预连接的服务端地址 */server_addr.sin_family = AF_INET;server_addr.sin_port = htons(SERVER_PORT);server_addr.sin_addr.s_addr = inet_addr(SERVER_HOST);rt_memset(&(server_addr.sin_zero), 0, sizeof(server_addr.sin_zero));rt_uint8_t *rec_buf = rt_calloc(1, REC_BUF_LEN);while (1) {/*初始化连接*/sockfd = socket(AF_INET, SOCK_STREAM, 0);if (sockfd < 0) {LOG_W("init socket is failed: %d;waiting 1s", sockfd);rt_thread_mdelay(1000);continue;}if (bind(sockfd, (struct sockaddr *) &client_addr, sizeof(struct sockaddr)) < 0) {LOG_W("socket bind failed.\n");goto __close_socket;}result = connect(sockfd, (struct sockaddr *) &server_addr, sizeof(struct sockaddr));if (result < 0) {LOG_W("connect is failed: %d;waiting 1s", result);goto __close_socket;}/*配置成非阻塞模式*/int val = 1;ioctlsocket(sockfd, FIONBIO, &val);client_rec: /*接收标签*/result = recv(sockfd, rec_buf, REC_BUF_LEN, 0);if (result == 0) { /*表示连接关闭*/LOG_I("server(%s) reject connected or closed", SERVER_HOST);goto __close_socket;} else if (result == -1) { /*表示未接收到数据*/rt_thread_mdelay(10);goto client_rec;} else if (result > 0) {/*连接成功*/if (send(sockfd, msg, strlen(msg), 0) == strlen(msg)) {goto client_rec;} else {goto __close_socket;}} else {/*todo 逻辑上不会执行到此处*/LOG_E("unknown result: %d", result);goto __close_socket;}__close_socket:closesocket(sockfd);rt_thread_mdelay(1000);}rt_free(rec_buf);}int lwip_test() {mq_rec = rt_thread_create("lwip_test",_th_entity,RT_NULL,1024,15,20);if (mq_rec) {rt_thread_startup(mq_rec);}return RT_EOK;}INIT_APP_EXPORT(lwip_test);#endif

设置接收非阻塞函数记录分析