Skip to content

Instantly share code, notes, and snippets.

@Mr00Anderson
Created November 18, 2020 16:32
Show Gist options
  • Save Mr00Anderson/ac2b491457cf9bc1815543c9afd70983 to your computer and use it in GitHub Desktop.
Save Mr00Anderson/ac2b491457cf9bc1815543c9afd70983 to your computer and use it in GitHub Desktop.
package app.virtualhex.network.packets;
import app.virtualhex.network.RawWebSocketsServerSession;
import app.virtualhex.network.RawWebSocketsSession;
import java.nio.ByteBuffer;
public class LatencyCheck extends AbstractPacket {
public static final int PACKET_ID = 1;
public static final String NAME = "LatencyCheck";
public LatencyCheck() {
super(PACKET_ID, NAME);
}
@Override
public void read(RawWebSocketsSession session, ByteBuffer in) {
if(session.isServer()){
RawWebSocketsServerSession serverSession = (RawWebSocketsServerSession) session;
serverSession.replyReceived = true;
long replyTime = System.currentTimeMillis();
session.updateAliveReplyTime(replyTime);
// Write a reply packet
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.put((byte) 1);
buffer.put((byte) Request.LATENCY_UPDATE.ordinal());
buffer.putShort((short) session.latency);
buffer.rewind();
session.writeBinaryFrame(buffer);
} else {
byte b = in.get();
Request[] values = Request.values();
if(b > values.length){
// TODO Error
} else {
Request value = values[b];
switch (value) {
case LATENCY_CHECK: {
session.writeBinaryFrame(ByteBuffer.wrap(new byte[]{PACKET_ID, (byte) Request.LATENCY_REPLY.ordinal()}));
break;
}
case LATENCY_UPDATE: {
short latency = in.getShort();
session.updateLatency(latency);
System.out.println("Client " + latency);
break;
}
}
}
}
}
public enum Request {
LATENCY_CHECK,
LATENCY_REPLY,
LATENCY_UPDATE
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment