protected void messageReceived(ChannelHandlerContext ctx, StompFrame frame) throws Exception {
String subscrReceiptId = "001";
String disconReceiptId = "002";
switch (frame.command()) {
case CONNECTED:
StompFrame subscribeFrame = new DefaultStompFrame(StompCommand.SUBSCRIBE);
subscribeFrame.headers().set(StompHeaders.DESTINATION, StompClient.TOPIC);
subscribeFrame.headers().set(StompHeaders.RECEIPT, subscrReceiptId);
subscribeFrame.headers().set(StompHeaders.ID, "1");
System.out.println("connected, sending subscribe frame: " + subscribeFrame);
state = ClientState.AUTHENTICATED;
ctx.writeAndFlush(subscribeFrame);
break;
case RECEIPT:
String receiptHeader = frame.headers().getAndConvert(StompHeaders.RECEIPT_ID);
if (state == ClientState.AUTHENTICATED && receiptHeader.equals(subscrReceiptId)) {
StompFrame msgFrame = new DefaultStompFrame(StompCommand.SEND);
msgFrame.headers().set(StompHeaders.DESTINATION, StompClient.TOPIC);
msgFrame.content().writeBytes("some payload".getBytes());
System.out.println("subscribed, sending message frame: " + msgFrame);
state = ClientState.SUBSCRIBED;
ctx.writeAndFlush(msgFrame);
} else if (state == ClientState.DISCONNECTING && receiptHeader.equals(disconReceiptId)) {
System.out.println("disconnected");
ctx.close();
} else {
throw new IllegalStateException("received: " + frame + ", while internal state is " + state);
}
break;
case MESSAGE:
if (state == ClientState.SUBSCRIBED) {
System.out.println("received frame: " + frame);
StompFrame disconnFrame = new DefaultStompFrame(StompCommand.DISCONNECT);
disconnFrame.headers().set(StompHeaders.RECEIPT, disconReceiptId);
System.out.println("sending disconnect frame: " + disconnFrame);
state = ClientState.DISCONNECTING;
ctx.writeAndFlush(disconnFrame);
}
break;