Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
mischa committed Sep 27, 2024
1 parent 9c7ada3 commit e6b5379
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
1 change: 1 addition & 0 deletions kcp2k/kcp2k/highlevel/KcpHeader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public enum KcpHeaderReliable : byte
// we already have a KcpHeader for reliable messages.
// ping is only used to keep it alive, so latency doesn't matter.
Ping = 2,
Pong = 4, // '4' not '3' in order to keep backwards compatibility
Data = 3,
}

Expand Down
46 changes: 45 additions & 1 deletion kcp2k/kcp2k/highlevel/KcpPeer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,13 @@ void TickIncoming_Connected(uint time)
case KcpHeaderReliable.Ping:
{
// ping keeps kcp from timing out. do nothing.
// safety: don't reply with pong message before authenticated.
break;
}
case KcpHeaderReliable.Pong:
{
// ping keeps kcp from timing out. do nothing.
// safety: don't handle pong message before authenticated.
break;
}
case KcpHeaderReliable.Data:
Expand Down Expand Up @@ -417,6 +424,28 @@ void TickIncoming_Authenticated(uint time)
}
case KcpHeaderReliable.Ping:
{
// ping includes the sender's local time for RTT calculation.
// simply send it back to the sender.
if (message.Count == 4)
{
Utils.Decode32U(message.Array, message.Offset, out uint pingTimestamp);
SendPong(pingTimestamp);
}
break;
}
case KcpHeaderReliable.Pong:
{
if (message.Count == 4)
{
Utils.Decode32U(message.Array, message.Offset, out uint originalTimestamp);
if (time >= originalTimestamp)
{
uint rtt = time - originalTimestamp;
Log.Warning($"[KCP] {GetType()}: RTT={rtt}ms");
}
}
// TODO calculate RTT

// ping keeps kcp from timing out. do nothing.
break;
}
Expand Down Expand Up @@ -736,7 +765,22 @@ public void SendData(ArraySegment<byte> data, KcpChannel channel)

// ping goes through kcp to keep it from timing out, so it goes over the
// reliable channel.
void SendPing() => SendReliable(KcpHeaderReliable.Ping, default);
readonly byte[] pingData = new byte[4]; // 4 bytes timestamp
void SendPing()
{
// when sending ping, include the local timestamp so we can
// calculate RTT from the pong.
Utils.Encode32U(pingData, 0, time);
SendReliable(KcpHeaderReliable.Ping, pingData);
}

void SendPong(uint pingTimestamp)
{
// when sending ping, include the local timestamp so we can
// calculate RTT from the pong.
Utils.Encode32U(pingData, 0, pingTimestamp);
SendReliable(KcpHeaderReliable.Pong, pingData);
}

// send disconnect message
void SendDisconnect()
Expand Down

0 comments on commit e6b5379

Please sign in to comment.