How can I use TCP Keep Alive function?


#1

When TCP connection is established, if SEND_KEEP command is provided to command register, 1byte data is transmitted to the peer.
If connection is closed, and no response is received, timeout interrupt occurs.
The period for sending TCP Keep Alive packet, can be decided at the firmware.

thanks :slight_smile:


#2

Auto keepalive function should be placed after Socket open and before connection.

ex)

void SetAutoKeepAlive(sn, time) // time > 0
{
    setSn_KPALVTR(sn, time);
    printf("Sn:%d - kpalvtime:%dsec\r\n",sn, 5*getSn_KPALVTR(sn));
}
int32_t loopback_tcps(uint8_t sn, uint8_t* buf, uint16_t port)
{
    int32_t ret;
    uint16_t size = 0, sentsize=0;
    switch(getSn_SR(sn)) {
        case SOCK_ESTABLISHED :
            if(getSn_IR(sn) & Sn_IR_CON) {
                printf("%d:Connected\r\n",sn);
                setSn_IR(sn,Sn_IR_CON);
            }
            if((size = getSn_RX_RSR(sn)) > 0) {
                if(size > DATA_BUF_SIZE) size = DATA_BUF_SIZE;
                //Data recieve
                ret = recv(sn,buf,size);
                if(ret <= 0) return ret;
                sentsize = 0;
                while(size != sentsize) {
                    //Data send
                    ret = send(sn,buf+sentsize,size-sentsize);
                    //If error occured
                    if(ret < 0) {
                    	close(sn);
                        return ret;
                    }
                    sentsize += ret; // Don't care SOCKERR_BUSY, because it is zero.
                }
            }
            break;
        case SOCK_CLOSE_WAIT :
            printf("%d:CloseWait\r\n",sn);
            if((ret=disconnect(sn)) != SOCK_OK) return ret;
            printf("%d:Closed\r\n",sn);
            break;
        case SOCK_INIT :
            printf("%d:Listen, port [%d]\r\n",sn, port);
            if( (ret = listen(sn)) != SOCK_OK) return ret;
            break;
        case SOCK_CLOSED:
            printf("%d:LBTStart\r\n",sn);
            if((ret=socket(sn,Sn_MR_TCP,port,0x00)) != sn)
                return ret;
            printf("%d:Opened\r\n",sn);

            SetAutoKeepAlive(sn, 2); // set Auto keepalive 10sec(2*5)

            break;
        default:
        break;
    }
    return 1;
}

thank you! :slight_smile: