Example of simple TCP server?
Posted: Fri Apr 27, 2018 5:11 pm
Hi,
I'm looking for examples of TCP server.
I need to read-write data over tcp: esp32 starts as wifi softap, then I connect from android phone and start some android tcp client.
Then I can exchanging data.
I have done wifi section and make some tcp connection.
Problem is that tcp server droping connection each time I send data from phone.
Here is my code:
I tried not to closing connection, but then I cant exchange data.
I'm looking for examples of TCP server.
I need to read-write data over tcp: esp32 starts as wifi softap, then I connect from android phone and start some android tcp client.
Then I can exchanging data.
I have done wifi section and make some tcp connection.
Problem is that tcp server droping connection each time I send data from phone.
Here is my code:
Code: Select all
// handle connection
static void netconn_handler(struct netconn *conn)
{
struct netbuf *inbuf;
char *buf;
uint16_t buflen;
err_t err;
err = netconn_recv(conn, &inbuf);
printf("net connection received\n");
if(err == ERR_OK)
{
netbuf_data(inbuf, (void**)&buf, &buflen);
memcpy(MyData.TCP_Buf, buf, buflen);
MyData.TCP_conn = true;
MyData.TCP_len = buflen;
MyData.TCP_got_packet = true;
ESP_LOGI(TCP_TAG, "TCP_to_UART_write len:%d\n data:%s", MyData.TCP_len, (uint8_t *)MyData.TCP_Buf);
RS485_send_data(E_TCP_BUFFER);
printf("RS485_send_data sent\n");
if (MyData.UART_got_packet == true)
{
MyData.UART_got_packet = false;
netconn_write(conn, MyData.TCP_Buf, MyData.TCP_len, NETCONN_NOCOPY);
ESP_LOGI(TCP_TAG, "TCP_to_UART_write len:%d\n data:%s", MyData.TCP_len, (uint8_t *)MyData.TCP_Buf);
}
}
// close the connection and free the buffer
netconn_close(conn);
MyData.TCP_conn = false;
printf("connection in conn handler closed\n");
netbuf_delete(inbuf);
}
//tcp server
static void tcp_server_task(void *pvParameters)
{
struct netconn *conn, *newconn;
err_t err;
conn = netconn_new(NETCONN_TCP);
netconn_bind(conn, NULL, TCP_PORT);
netconn_listen(conn);
printf("TCP Server listening port:%d\n",TCP_PORT);
do
{
err = netconn_accept(conn, &newconn);
printf("New client connected\n");
if (err == ERR_OK) {
printf("Process connection\n");
netconn_handler(newconn);
FlowMeterData.TCP_conn = false;
printf("Process connection end\n");
netconn_delete(newconn);
printf("net connection deleted\n");
}
vTaskDelay(1); //allows task to be pre-empted
} while(err == ERR_OK);
printf("Closing tcp\n");
netconn_close(conn);
netconn_delete(conn);
printf("\n");
}
I tried not to closing connection, but then I cant exchange data.