|
| 1 | +package net.rcode.wsclient; |
| 2 | + |
| 3 | +import java.nio.charset.Charset; |
| 4 | + |
| 5 | +public class Message { |
| 6 | + private static final Charset UTF8=Charset.forName("UTF8"); |
| 7 | + |
| 8 | + // -- message opcodes |
| 9 | + public static final int OPCODE_CONTINUATION=0; |
| 10 | + public static final int OPCODE_CLOSE=1; |
| 11 | + public static final int OPCODE_PING=2; |
| 12 | + public static final int OPCODE_PONG=3; |
| 13 | + public static final int OPCODE_TEXT=4; |
| 14 | + public static final int OPCODE_BINARY=5; |
| 15 | + |
| 16 | + |
| 17 | + private int opcode; |
| 18 | + private byte[] messageData; |
| 19 | + |
| 20 | + public Message(int opcode, byte[] messageData) { |
| 21 | + this.opcode=opcode; |
| 22 | + this.messageData=messageData; |
| 23 | + } |
| 24 | + |
| 25 | + public boolean isText() { |
| 26 | + return opcode==OPCODE_TEXT; |
| 27 | + } |
| 28 | + |
| 29 | + public String getMessageText() { |
| 30 | + if (isText()) return new String(messageData, UTF8); |
| 31 | + else throw new IllegalStateException("Not text based message"); |
| 32 | + } |
| 33 | + |
| 34 | + public int getOpcode() { |
| 35 | + return opcode; |
| 36 | + } |
| 37 | + |
| 38 | + public byte[] getMessageData() { |
| 39 | + return messageData; |
| 40 | + } |
| 41 | + |
| 42 | + @Override |
| 43 | + public String toString() { |
| 44 | + if (opcode==OPCODE_TEXT) return getMessageText(); |
| 45 | + else if (messageData!=null ){ |
| 46 | + StringBuilder ret=new StringBuilder(); |
| 47 | + for (byte b: messageData) { |
| 48 | + ret.append(Integer.toHexString(b)).append(" "); |
| 49 | + } |
| 50 | + return ret.toString(); |
| 51 | + } else return ""; |
| 52 | + } |
| 53 | +} |
0 commit comments