BL602&BL604 TCP SERVER
在上一节我们成功实现了模块作为TCP client接入到TCP server实现通讯,这节我们来实现模块作为TCP server,让其他TCP client接入实现通讯。
例程地址:
https://github.com/SmartArduino/Doiting_BL/tree/master/examples/WIFI_SERVER
在前面实现wif连接的基础上,在wifi连接成功后创建TCPserver任务。
//TCP server任务 static void tcp_server(void *arg) { char databuff[512]; uint8_t *recv_data; uint32_t sin_size; int sock = -1, connected, bytes_received; struct sockaddr_in server_addr, client_addr; char *host = (char*)arg; LOGE(TAG," start tcp_server "); recv_data = (uint8_t *)pvPortMalloc(IPERF_BUFSZ); if (recv_data == NULL) { LOGE(TAG,"No memory"); goto __exit; } (void) host; sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0) { LOGE(TAG,"Socket error"); goto __exit; } server_addr.sin_family = AF_INET; server_addr.sin_port = htons(IPERF_PORT); server_addr.sin_addr.s_addr = INADDR_ANY;//INADDR_ANY; memset(&(server_addr.sin_zero), 0x0, sizeof(server_addr.sin_zero)); if (bind(sock, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1) { LOGE(TAG,"Unable to bind"); goto __exit; } if (listen(sock, 5) == -1) { LOGE(TAG,"Listen error"); goto __exit; } while (1) { sin_size = sizeof(struct sockaddr_in); connected = accept(sock, (struct sockaddr *)&client_addr, (socklen_t *)&sin_size); LOGI(TAG,"new client connected from (%s, %d)", inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port)); { int flag = 1; setsockopt(connected, IPPROTO_TCP, /* set option at TCP level */ TCP_NODELAY, /* name of option */ (void *) &flag, /* the cast is historical cruft */ sizeof(int)); /* length of option value */ } while (1) { memset(databuff, 0x00, sizeof(databuff)); bytes_received= recv(connected, databuff, sizeof(databuff), 0); if (bytes_received <= 0) break; send(connected, databuff, strlen(databuff), 0);//将接收到的消息发送回客户端 LOGE(TAG, "recv: %s", databuff); } if (connected >= 0) closesocket(connected); connected = -1; } __exit: if (sock >= 0) closesocket(sock); if (recv_data) vPortFree(recv_data); if (arg) vPortFree(arg); }
void wifi_event_handler(wifi_event_indicate_t event){ switch (event) { case WIFI_EVENT_CONNECT: LOGE(TAG, "wifi_connect"); //WIFI连接成功创建TCP server 任务 if (!tcpc_task_handle) { if (xTaskCreate(tcp_server, "tcp_server", TCPC_TASK_SIZE, NULL, 2, &tcpc_task_handle) != pdPASS) { LOGE(TAG, "create tcp_server fail"); } } break; case WIFI_EVENT_DISCONNECT: LOGE(TAG, "wifi_disconnect"); break; default: LOGE(TAG, "wifi_event: %d",event); break; } }
编译好程序后,将固件烧录到模块后复位,观察串口输出,当连接上wifi后,用TCP测试工具建立TCP client连接。
创建成功后点击连接,连接成功后串口会输出该连接的IP和端口
连接成功后进行通讯测试,在测试工具中发送的数据,设备在接收到数据后会将数据发送回客户端,同时串口会打印出数据。