1 46 package org.mr.core.net.messages; 47 48 import java.net.SocketAddress ; 49 import java.nio.ByteBuffer ; 50 51 60 61 public class NetworkMessage { 62 public static int NET_HEADERLEN = 3; 63 64 protected static byte NET_ID = 1; 65 protected static byte NET_KEEPALIVE = 2; 66 67 private byte type; 68 private short length; 69 private SocketAddress source; 71 private SocketAddress dest; 72 private boolean isTCP; 73 74 protected NetworkMessage(byte type, short length) { 75 this.type = type; 76 this.length = length; 77 } 79 protected NetworkMessage(ByteBuffer buf) { 80 this.type = buf.get(); 81 this.length = buf.getShort(); 82 } 83 84 public void write(ByteBuffer buf) { 85 buf.put(this.type); 86 buf.putShort(this.length); 87 } 88 89 public int getLength() { 90 return this.length; 91 } 92 93 public static NetworkMessage create(byte[] data, boolean isTCP, 94 SocketAddress source, 95 SocketAddress dest) { 96 return create(ByteBuffer.wrap(data), isTCP, source, dest); 97 } 98 99 public static NetworkMessage create(ByteBuffer buf, boolean isTCP, 100 SocketAddress source, 101 SocketAddress dest) { 102 buf.mark(); 103 byte type = buf.get(); 104 buf.reset(); 105 106 NetworkMessage ret = null; 107 if (type == NET_ID) { 108 ret = new NetworkMessageID(buf); 109 } else if (type == NET_KEEPALIVE) { 110 ret = new NetworkMessageKeepalive(buf); 111 } 112 113 if (ret != null) { 114 ret.setTCP(isTCP); 115 ret.setSource(source); 116 ret.setDest(dest); 117 } 118 return ret; 119 } 120 121 public static void create(ByteBuffer buf, boolean isTCP, 122 SocketAddress source, SocketAddress dest, 123 NetworkMessageHandler handler) { 124 buf.mark(); 125 byte type = buf.get(); 126 buf.reset(); 127 128 if (type == NET_ID) { 129 NetworkMessageID id = new NetworkMessageID(buf); 130 id.setTCP(isTCP); 131 id.setSource(source); 132 id.setDest(dest); 133 handler.handleNetMessageID(id); 134 } 135 } 136 137 140 public SocketAddress getDest() { 141 return dest; 142 } 143 144 147 public void setDest(SocketAddress dest) { 148 this.dest = dest; 149 } 150 151 154 public boolean isTCP() { 155 return isTCP; 156 } 157 158 161 public void setTCP(boolean isTCP) { 162 this.isTCP = isTCP; 163 } 164 165 168 public SocketAddress getSource() { 169 return source; 170 } 171 172 175 public void setSource(SocketAddress source) { 176 this.source = source; 177 } 178 } | Popular Tags |