users@websocket-spec.java.net

[jsr356-users] How to determine Text vs Binary with @WebSocketMessage

From: Joakim Erdfelt <joakim_at_intalio.com>
Date: Wed, 20 Feb 2013 10:27:57 -0700

With the Decoder/Encoder framework, it seems to be possible to setup
ambiguous configurations with regards to use of Text vs Binary messages.

Take this example.

// - DualDecoder.java

import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;

import javax.websocket.DecodeException;
import javax.websocket.Decoder;

public class DualDecoder implements Decoder.Text<Integer>,
Decoder.Binary<Integer>
{
    @Override
    public Integer decode(ByteBuffer bytes) throws DecodeException
    {
        try
        {
            return bytes.getInt();
        }
        catch (BufferUnderflowException e)
        {
            throw new DecodeException(bytes,"Unable to read int from binary
message",e);
        }
    }

    @Override
    public Integer decode(String s) throws DecodeException
    {
        try
        {
            return Integer.parseInt(s);
        }
        catch (NumberFormatException e)
        {
            throw new DecodeException(s,"Unable to parse Integer",e);
        }
    }

    @Override
    public boolean willDecode(ByteBuffer bytes)
    {
        if (bytes == null)
        {
            return false;
        }
        return bytes.remaining() >= 4;
    }

    @Override
    public boolean willDecode(String s)
    {
        if (s == null)
        {
            return false;
        }

        try
        {
            Integer.parseInt(s);
            return true;
        }
        catch (NumberFormatException e)
        {
            return false;
        }
    }
}


// - IntSocket.java

import java.io.IOException;

import javax.websocket.EncodeException;
import javax.websocket.Session;
import javax.websocket.WebSocketClient;
import javax.websocket.WebSocketMessage;

@WebSocketClient(decoders = { DualDecoder.class })
public class IntSocket
{
    @WebSocketMessage
    public void onInt(Session session, int value)
    {
        try
        {
            session.getRemote().sendObject(value);
        }
        catch (IOException | EncodeException e)
        {
            e.printStackTrace();
        }
    }
}

// -- snip --

With this scenario, the IntSocket.onInt(session, value) has no idea if the
incoming message was Binary or Text.
Is this intentional?

--
Joakim Erdfelt <joakim_at_intalio.com>
webtide.com <http://www.webtide.com/>
Developer advice, services and support
from the Jetty & CometD experts
eclipse.org/jetty - cometd.org