2
votes

About the Codename One Websocket cn1lib, I saw your lesson on the Whatsapp clone, however the code you proposed is for a complete app. Could you provide a simpler self-enclosed example of use of Websocket cn1lib with client-side code (Codename One code to send and receive messages) and server-side code (Spring Boot Java 8 to receive and send messages)?

I’m particulary interested in a simple Spring Boot example that interacts with Codename One, as start point to better understand and learn websocket.

Thank you

1

1 Answers

1
votes

It would look roughly like this on the server:

public class WebSocketServer extends TextWebSocketHandler {
    private static final Object LOCK = new Object();
    private Map<String, WebSocketSession> sessions = new HashMap<>();

    @Override
    protected void handleTextMessage(WebSocketSession session,
                                     TextMessage message) throws Exception {
        Gson gson = new Gson();
        MyDTO parsed = gson.fromJson(message.getPayload(), MyDTO.class);
        // ... do stuff with incoming message

        synchronized(LOCK) {
            if(!sessions.contains(parsed.getId()) { 
                sessions.put(parsed.getId(), session);
            }
        }
    }

    public boolean sendMessage(String destId, String json) {
        Session s = null;
        synchronized(LOCK) {
            s = sessions.get(destId);
        }
        if (s != null && s.isOpen()) {
            try {
                s.sendMessage(new TextMessage(s));
                return true;
            } catch (IOException e) {
                synchronized(LOCK) {
                   sessions.remove(destId);
                }
            }
        }
        return false;
    }
}