5 years, 9 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

5 years, 9 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...

Hi, Jan, It is not work...

when I close s socket and accept another, it printf :connect. However, mbed OS had a "FaultType: HardFault" when I send data to MCU in PC.

My application need more than one scoket and close it when there is no data in seconds .Does it action?

posted by shang dong 23 Jul 2018