Skip to content
徐昊 edited this page Nov 10, 2018 · 5 revisions

Send Heartbeat

//Class A:
//...Define the heartbeat data type required by the heartbeat manager...
public class PulseData implements IPulseSendable {
	private String str = "pulse";

    @Override
    public byte[] parse() {
    //Build the byte array according to the server's parsing rules
        byte[] body = str.getBytes(Charset.defaultCharset());
        ByteBuffer bb = ByteBuffer.allocate(4 + body.length);
        bb.order(ByteOrder.BIG_ENDIAN);
        bb.putInt(body.length);
        bb.put(body);
        return bb.array();
    }
}

//Class B:
private IConnectionManager mManager;
private PulseData mPulseData = new PulseData;
@Override
public void onSocketConnectionSuccess(ConnectionInfo info, String action) {
     //Chain programming call. Set heartbeat data for the heartbeat manager. 
     //A connection only has a heartbeat manager, so the data is set only once. 
     //If disconnected, please set it again.
     OkSocket.open(info)
     	.getPulseManager()
     	.setPulseSendable(mPulseData)
     	.pulse();//Start the heartbeat. 
}

The Heartbeat Feed Dog

  • Feed the dog. Because our client needs to know the Socket server received the heartbeat data, so the server needs to reply the client after receiving the heartbeat data, called it ACK. We need to feed the dog, or when more than a certain number of times the heartbeat data, but did not supply the dog food, the dog will connect the disconnect reconnection, we call it dog dead.
private IConnectionManager mManager;
//When the client receives the message
@Override
public void onSocketReadResponse(ConnectionInfo info, String action, OriginalData data) {
	if(mManager != null && /*It's the heartbeat return package*/){
		//Whether it is a heartbeat return package, 
                //you need to resolve the data returned by the server to know
		//Feed dog
	    mManager.getPulseManager().feed();
	}
}

Manual Trigger Heartbeat

private IConnectionManager mManager;
//...in anywhere...
mManager = OkSocket.open(info);
if(mManager != null){
	PulseManager pulseManager = mManager.getPulseManager();
	//Manually trigger a heartbeat 
        //(mainly used for situations requiring manual control of trigger timing)
	pulseManager.trigger();
}