Le 24/02/15 08:39, Abeer Al-Anazi a écrit :
> Did you mean like this:
> public class requestEncoder implements ProtocolEncoder {
> @Override
> public void encode(IoSession session, Object message,
> ProtocolEncoderOutput out) throws Exception {
> byte b;
> IoBuffer buffer = IoBuffer.allocate(220, false);
> buffer.setAutoExpand(true);
> if (message instanceof Long )
> { b = '@';
> long controllerCurrentLoad= (Long) message;
> buffer.put (b);
> buffer.putLong(controllerCurrentLoad);
>
> }
Long inherit from Object, this it will be serialized twice. Use a else here.
> if ( message instanceof Object )
> {
> b = '&';
> controllerInfo request = (controllerInfo ) message;
> buffer.put (b);
> buffer.putObject(request.getControllerName());
> buffer.putObject(request.getBackupControllers());
> buffer.putLong(request.getControllerCapacity());
>
>
> }
>
>
> buffer.flip();
> out.write(buffer);
>
> }
> the decoder will be:
> protected boolean doDecode(IoSession session, IoBuffer in,
> ProtocolDecoderOutput out) throws Exception {
> byte b = 0 ;
> String cName = null;
> HashMap <String, Long> backupControllers = new HashMap <String,
> Long>() ;
> long controllerCapacity=0;
> long controllerCurrentLoad = 0;
>
> while (in.hasRemaining())
> {
> b = in.get();
>
> if (b == '&')
>
> {
> cName =(String) in.getObject();
> @SuppressWarnings("unchecked")
> HashMap<String, Long> bc= (HashMap<String, Long>) in.getObject();
> backupControllers = bc;
> controllerCapacity = in.getLong();
>
> }
>
> else if (b == '@')
> {
>
> controllerCurrentLoad = in.getLong();
>
> }
>
> }
>
> controllerInfo request = new controllerInfo (cName, backupControllers,
> controllerCapacity);
> request.setControllerLoad(controllerCurrentLoad);
> out.write(request);
>
> return false;
> }
> I tested it and it read the object, and it did not read the long.
Y-Your decoder is almost correct, except that you a-have to deal with
TCP fragmentation : you have no guarantee whatsoever that the data will
be transmitted in one single block of bytes. You have to take care of
that, for instance by adding the length of what you have sent before the
data itself. In a way, yu can use this length to determinate what kind
of object you have received : a long will be stored in 8 bytes, so if
the first 4 bytes contains 8, it's a long, otherwise it's an Object.
But, yes, this is the way to do, beside some obvious bug that is easy to
fix.
>