Skip to content
winlin edited this page Feb 21, 2017 · 12 revisions

Usage

The basic usage for application to integrate with KCP:

  1. Create a KCP object:

    // Allocate a KCP object and initialize it.
    // @param conv An IUINT32 number identifies the session id. 
    // .   Same as TCP conv, both peer(sender and receiver) must use the same conv id for packet identify.
    // @param user A user specified handler, pass-by param for callback.
    ikcpcb *kcp = ikcp_create(conv:IUINT32, user:void*);
  2. Setup the callback function:

    // The callback of KCP to send out data over concrete transport, for instance, over UDP.
    // @param buff/len The bytes in buffer to send.
    // @param user A user specified handler, setup by ikcp_create.
    int udp_output(const char *buf, int len, ikcpcb *kcp, void *user)
    {
      ....
    }
    // Use this callback for the KCP object.
    ikcp_setoutput(kcp, udp_output);
  3. Update the states of KCP:

    // Every some time, such as 10ms, call this method to update the status of KCP.
    // @param current The current clock time in milliseconds.
    // @remark User can use ikcp_check for high performance update.
    ikcp_update(kcp, current);
  4. Notify KCP when data received from peer:

    // For examle, when got a UDP packet, notify KCP.
    // @param data The received packet.
    // @param size The size of packet.
    ikcp_input(kcp, data, size);
  5. Done:

    User can now use ikcp_send to send packets to peer. Peer can use ikcp_recv to receive packets from peer.

Config KCP

The default mode of KCP is a standard ARQ, user can setup the bellow options for low latency:

  1. Work mode

    int ikcp_nodelay(ikcpcb *kcp, int nodelay, int interval, int resend, int nc)
    • nodelay: Whether enable nodelay mode. 0: Off; 1: On.
    • interval: The internal interval in milliseconds, such as 10ms or 30ms.
    • resend: Whether enable fast retransmit mode. 0: Off; 2: Retransmit when missed in 2 ACK.
    • nc: Whether disable the flow control. 0: Enable. 1: Disable.
    • For normal mode, like TCP: ikcp_nodelay(kcp, 0, 40, 0, 0);
    • For high efficient transport: ikcp_nodelay(kcp, 1, 10, 2, 1);
  2. Window size

    int ikcp_wndsize(ikcpcb *kcp, int sndwnd, int rcvwnd);

    Setup the max send or receive window size in packets, default to 32 packets. Similar to TCP SO_SNDBUF and SO_RECVBUF, but they are in bytes, while ikcp_wndsize in packets.

  3. MTU

    The MTU(Maximum Transmission Unit) default to 1400 bytes, which can be set by ikcp_setmtu. Notice that KCP never probe the MTU, user must tell KCP the right MTU to use if need.

  4. Minimum RTO

    Both TCP and KCP use minimum RTO, for example, when calculated RTO is 40ms but default minimum RTO is 100ms, then KCP never detect the dropped packet util after 100ms. The default value of minimum RTO is 100ms for normal mode, while 30ms for high efficient transport. User can setup minimum RTO by:

    kcp->rx_minrto = 10;
Clone this wiki locally