2019-03-04 06:24 PM
What I want to do is create a TCP server that uses stm32f746-disco until the client sends a shutdown command.
So, I created an echo server with lwip socket referring to the example, and when I close it, the connection with client ends.
I think that if I remove the close, it should be repetitive, but it only works the first time and then stop.
Below is my code, please let me know how to fix it.
void MX_LWIP_Init(void*params)
{
/* IP addresses initialization */
IP_ADDRESS[0] = 192;
IP_ADDRESS[1] = 168;
IP_ADDRESS[2] = 0;
IP_ADDRESS[3] = 201;
NETMASK_ADDRESS[0] = 255;
NETMASK_ADDRESS[1] = 255;
NETMASK_ADDRESS[2] = 255;
NETMASK_ADDRESS[3] = 0;
GATEWAY_ADDRESS[0] = 192;
GATEWAY_ADDRESS[1] = 168;
GATEWAY_ADDRESS[2] = 0;
GATEWAY_ADDRESS[3] = 1;
tcpip_init(NULL, NULL);
IP4_ADDR(&ipaddr, IP_ADDRESS[0], IP_ADDRESS[1], IP_ADDRESS[2], IP_ADDRESS[3]);
IP4_ADDR(&netmask, NETMASK_ADDRESS[0], NETMASK_ADDRESS[1] , NETMASK_ADDRESS[2], NETMASK_ADDRESS[3]);
IP4_ADDR(&gw, GATEWAY_ADDRESS[0], GATEWAY_ADDRESS[1], GATEWAY_ADDRESS[2], GATEWAY_ADDRESS[3]);
netif_add(&gnetif, &ipaddr, &netmask, &gw, NULL, ðernetif_init, &tcpip_input);
netif_set_default(&gnetif);
if (netif_is_link_up(&gnetif))
{
netif_set_up(&gnetif);
}
else
{
netif_set_down(&gnetif);
}
TCP_socket_server_make();
while(1)
{
}
}
void TCP_socket_server_make()
{
sys_thread_new("TCP_SS", TCP_socket_server_thread, NULL, 1024, 1);
}
static void TCP_socket_server_thread(void* arg)
{
int sock, newconn, size=0;
struct sockaddr_in address, remotehost;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
return;
}
address.sin_family = AF_INET;
address.sin_port = htons(502);
address.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (struct sockaddr *)&address, sizeof (address)) < 0)
{
return;
}
listen(sock, 5);
while (1)
{
newconn = accept(sock, (struct sockaddr *)&remotehost, (socklen_t *)&size);
TCP_Echo_server(newconn);
}
}
static void TCP_Echo_server(int conn)
{
int buflen = 1500;
int ret = 0;
int wet = 0;
unsigned char recv_buffer[1500];
ret = read(conn, recv_buffer, buflen);
if(ret < 0)
{
return;
}
if(ret>0)
{
wet = write(conn, recv_buffer, ret);
}
close(conn);
}
2019-03-04 08:57 PM
I solved this problem by applying various example code. But I do not know why it works normally. I have to study more.
I suppose that when the client receives the data it sends when it closes, it returns 0 in the read function.
static void TCP_Echo_server(int conn)
{
int buflen = 1500;
int ret = 0;
int wet = 0;
unsigned char recv_buffer[1500];
while((ret = read(conn, recv_buffer, buflen))!=0)
{
wet = write(conn, recv_buffer, ret);
}
close(conn);
}