p = Packet.parseFrom(readNextPacket(channel));
if (p.getType() != PacketType.ACK) {
throw new Exception("unexpected packet type when ack is expected");
}
Ack ack = Ack.parseFrom(p.getBody());
if (ack.getErrorCode() > 0) {
throw new Exception("something goes wrong when doing authentication: " + ack.getErrorMessage());
}
writeWithHeader(channel,
Packet.newBuilder()
.setType(PacketType.SUBSCRIPTION)
.setBody(Sub.newBuilder().setDestination(DESTINATION).setClientId("1").build().toByteString())
.build()
.toByteArray());
//
p = Packet.parseFrom(readNextPacket(channel));
ack = Ack.parseFrom(p.getBody());
if (ack.getErrorCode() > 0) {
throw new Exception("failed to subscribe with reason: " + ack.getErrorMessage());
}
for (int i = 0; i < 10; i++) {
writeWithHeader(channel,
Packet.newBuilder()
.setType(PacketType.GET)
.setBody(Get.newBuilder()
.setDestination(DESTINATION)
.setClientId("1")
.setFetchSize(10)
.build()
.toByteString())
.build()
.toByteArray());
p = Packet.parseFrom(readNextPacket(channel));
long batchId = -1L;
switch (p.getType()) {
case MESSAGES: {
Messages messages = Messages.parseFrom(p.getBody());
batchId = messages.getBatchId();
break;
}
case ACK: {
ack = Ack.parseFrom(p.getBody());
if (ack.getErrorCode() > 0) {
throw new Exception("failed to subscribe with reason: " + ack.getErrorMessage());
}
break;
}
default: {
throw new Exception("unexpected packet type: " + p.getType());