ESP32-C3-MINI socket连接
ESP32-C3-MINI socket连接
C3为服务端,一个设备不停的断开连接再重新连接C3,站点数也会增加,在断开连接时并不会减少站点数.导致多次以后,超过了最大站点连接数.请问有什么解决办法吗
Re: ESP32-C3-MINI socket连接
- for (;;)
- {
- // initialize file descriptor set
- FD_ZERO(&fdsr);
- FD_SET(listen_sock, &fdsr);
- // timeout setting
- tv.tv_sec = 60;
- tv.tv_usec = 0;
- // add active connection to fd set
- for (i = 0; i < BACKLOG; i++) {
- if (fd_A[i] != 0) {
- FD_SET(fd_A[i], &fdsr);
- }
- }
- //block here until listen_sock can read
- int ret = select(maxsockfd+1, &fdsr, NULL, NULL, &tv);
- if (ret < 0) {
- perror("select");
- break;
- } else if (ret == 0) {
- printf("timeout\n");
- continue;
- }
- // check every fd in the set and handle the recv()
- for (i = 0; i < conn_amount; i++)
- {
- if (FD_ISSET(fd_A[i], &fdsr))
- {
- ret = recv(fd_A[i], rx_buffer, sizeof(rx_buffer) - 1, 0);
- ret1= ret;
- station = i;
- if (ret <= 0)
- { // client close
- ESP_LOGE(TAG, "recv failed or connection closed: errno %d", errno);
- printf("client[%d] close\n", i);
- close(fd_A[i]);
- FD_CLR(fd_A[i], &fdsr);
- fd_A[i] = 0;
- // conn_amount=0;
- }
- else
- { // receive data
- //printf("star\n");
- if (ret < BUF_SIZE)
- memset(&rx_buffer[ret], '\0', 1);
- printf("client[%d] send:%s\n", i, rx_buffer);
- ctl_mode = rx_buffer[0];
- //Uart0Recv(i,rx_buffer,ret);
- /*int err = send(fd_A[i], rx_buffer, ret, 0);
- if (err < 0) {
- ESP_LOGE(TAG, "Error occured during sending: errno %d", errno);
- continue;
- }*/
- }
- }
- }
- // check whether a new connection comes and handler the new connection
- if (FD_ISSET(listen_sock, &fdsr)) {
- int connect_sock = accept(listen_sock, (struct sockaddr *)&client_addr, &addrLen);
- if (connect_sock <= 0) {
- perror("accept");
- continue;
- }
- ESP_LOGI(TAG, "Socket accepted");
- // add to fd queue
- if (conn_amount < BACKLOG)
- {
- fd_A[conn_amount++] = connect_sock;
- printf("new connection client[%d] %s:%d\n", conn_amount,
- inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
- if (connect_sock > maxsockfd)
- maxsockfd = connect_sock;
- }
- else {
- printf("max connections arrive, exit\n");
- send(connect_sock, "bye", 4, 0);
- close(connect_sock);
- continue;
- }
- }
- //showclient();
- }
- // when select() return error, close other connections
- for (i = 0; i < BACKLOG; i++) {
- ESP_LOGE(TAG, "Shutting down socket and restarting...");
- if (fd_A[i] != 0) {
- shutdown(fd_A[i], 0);
- close(fd_A[i]);
- }
- }
Re: ESP32-C3-MINI socket连接
你关闭 socket 的时候可以选择强制关闭 socket。 使用 SO_LINGER 选项。具体可以参考 viewtopic.php?f=13&t=20705
Who is online
Users browsing this forum: No registered users and 101 guests