Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
6 years, 5 months ago.
TCP Socket can not reconnect
there is a fault when I reconnect a server an send data to MCU used my pc. The frist time, it's OK. Why? here is the code section:
while(1) { /* Can handle x simultaneous connections */ if(srv.listen(1) == 0) { srv.accept(&client_sock, &client_addr); printf("Accepted %s:%d\n", client_addr.get_ip_address(), client_addr.get_port());
Thread::wait(10000); tmpcount = client_sock.recv(buffer, 1024); client_sock.TCPSocket(); printf("closed \n"); } }
1 Answer
6 years, 5 months ago.
Hi, in second run in your loop you want again accept a client without close the client from first loop. So your server waiting for new connection but your client is still connected...
Your code
while(1) { /* Can handle x simultaneous connections */ if(srv.listen(1) == 0) { srv.accept(&client_sock, &client_addr); printf("Accepted %s:%d\n", client_addr.get_ip_address(), client_addr.get_port()); Thread::wait(10000); tmpcount = client_sock.recv(buffer, 1024); client_sock.TCPSocket(); // close need here printf("closed \n"); } }
This is a standart way.
New pseudo code
while(1) { printf("\nWait for new connection...\n"); srv.accept(&client_sock, &client_addr); printf("Accepted %s:%d\n", client_addr.get_ip_address(), client_addr.get_port()); while(1) { tmpcount = client_sock.recv(buffer, 1024); if (tmpcount <= 0) break; printf("Received message from Client :'%s'\n",buffer);; } client_sock.close(); }
It's only my idea...