Java Websocket GWT

Java Websocket GWT

java

Para usar websocket en java y con GWT se debe trabajar en navegadores recientes y usar un contenedor de applicaciones que lo soporte como por ejemplo un tomcat 7.0.64 o más

Proyecto en GWT fuente https://github.com/realityforge/gwt-websockets

Ejemplo servidor websocket

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
//import java.util.logging.Logger;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.apache.log4j.Logger;

/**
 *
 * @author josorio Las librerias relacionadas con websocket deben ser providen
 * no se deben empaquetar para el tomcat.
 */
@ServerEndpoint(value = "/chat", subprotocols = {"superchat", "chat"})
public class ChatServer {

    private static final Logger LOG = Logger.getLogger(ChatServer.class.getName());
    private static Set<Session> peers = Collections.synchronizedSet(new HashSet<Session>());

    @OnOpen
    public void onOpen(final Session session) {
        LOG.error("onOpen(" + session.getId() + ")");
        peers.add(session);
    }

    @OnClose
    public void onClose(final Session session) {
        LOG.error("onClose(" + session.getId() + ")");
        final String id = session.getId();
        for (final Session peer : peers) {
            if (peer.getId().equals(session.getId())) {
                LOG.error("Se fue"); 
            } else {
                peer.getAsyncRemote().sendText(id + " Se fue " + session.getId());
            }
        }
        peers.remove(session);
    }

    @OnMessage
    public void onMessage(final String message, final Session session) {
        LOG.error("onMessage(" + message + "," + session.getId() + ")");
        final String id = session.getId();
        for (final Session peer : peers) {
            if (peer.getId().equals(session.getId())) {
                peer.getAsyncRemote().sendText("You said " + message);
            } else {
                peer.getAsyncRemote().sendText(id + " says " + message);
            }
        }
    }

    @OnMessage
    public void onBinaryMessage(final byte[] data, final Session session) {
        final String message = new String(data, Charset.forName("US-ASCII"));
        LOG.error("onBinaryMessage(" + message + "," + session.getId() + ")");
        final String id = session.getId();
        for (final Session peer : peers) {
            if (peer.getId().equals(session.getId())) {
                peer.getAsyncRemote().sendBinary(ByteBuffer.wrap(("You said " + message).getBytes()));
            } else {
                peer.getAsyncRemote().sendBinary(ByteBuffer.wrap((id + " says " + message).getBytes()));
            }
        }
    }

    /**
     * Mensaje para todos.
     * @param message 
     */
    public static void broadcastMessage(String message) {
        //System.out.println("-------------------------Broadcast---------------------------------");
        for (Session s : peers) {
            if (s.isOpen()) {
                try {
                    s.getBasicRemote().sendText(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Ejemplo cliente websocket java
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;

@ClientEndpoint
public class WebsocketClientEndpoint {

    Session userSession = null;
    private MessageHandler messageHandler;

    public WebsocketClientEndpoint(URI endpointURI) {
        try {
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            container.connectToServer(this, endpointURI);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Callback hook for Connection open events.
     *
     * @param userSession the userSession which is opened.
     */
    @OnOpen
    public void onOpen(Session userSession) {
        System.out.println("opening websocket");
        this.userSession = userSession;
    }

    /**
     * Callback hook for Connection close events.
     *
     * @param userSession the userSession which is getting closed.
     * @param reason the reason for connection close
     */
    @OnClose
    public void onClose(Session userSession, CloseReason reason) {
        System.out.println("closing websocket");
        this.userSession = null;
    }

    /**
     * Callback hook for Message Events. This method will be invoked when a client send a message.
     *
     * @param message The text message
     */
    @OnMessage
    public void onMessage(String message) {
        if (this.messageHandler != null) {
            this.messageHandler.handleMessage(message);
        }
    }

    /**
     * register message handler
     *
     * @param message
     */
    public void addMessageHandler(MessageHandler msgHandler) {
        this.messageHandler = msgHandler;
    }

    /**
     * Send a message.
     *
     * @param user
     * @param message
     */
    public void sendMessage(String message) {
        this.userSession.getAsyncRemote().sendText(message);
    }

    /**
     * Message handler.
     *
     * @author Jiji_Sasidharan
     */
    public static interface MessageHandler {

        public void handleMessage(String message);
    }
}

public class PruebasWSClient {

    /**
     * MAIN
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        
        try {            
            String uri = "ws://localhost:8084/veridian.taxis/chat";
            // open websocket
            final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI(uri));

            // add listener
            clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
                @Override
                public void handleMessage(String message) {
                    System.out.println(message);
                }
            });

            // send message to websocket
            clientEndPoint.sendMessage("{'event':'addChannel','channel':'ok_btccny_ticker'}");

            // wait 5 seconds for messages from websocket
            Thread.sleep(50000);
        } catch (InterruptedException ex) {
            System.err.println("InterruptedException exception: " + ex.getMessage());
//        } catch (URISyntaxException ex) {
//            System.err.println("URISyntaxException exception: " + ex.getMessage());
        } catch (Exception ex) {
            System.out.println("Error "+ex.getMessage());
            ex.printStackTrace();
//            Logger.getLogger(PruebasWSClient.class.getName()).log(Level.ERROR, null, ex);            
        }
    }

    

}
Cliente websocket GWT

Recomendado usar almenos GWT 2.6 <inherits name=”org.realityforge.gwt.websockets.WebSockets”/>

public class ExampleWS extends WebSocketListenerAdapter implements EntryPoint {

    private static final Logger LOG = Logger.getLogger(ExampleWS.class.getName());
    private HTML _messages;
    private ScrollPanel _scrollPanel;
    private Button _disconnect;
    private Button _connect;
    private Button _send;
    private CheckBox _subProtocol;

    @Override
    public void onModuleLoad() {
        final WebSocket webSocket = WebSocket.newWebSocketIfSupported();
        if (null == webSocket) {
            Window.alert("WebSocket not available!");
        } else {
            webSocket.setListener(this);
            final TextBox input = new TextBox();
            input.setValue("Greetings!");
            final CheckBox checkBox = new CheckBox("Binary?");
            _subProtocol = new CheckBox("Use sub-protocol?");
            _connect = new Button("Connect", new ClickHandler() {
                @Override
                public void onClick(final ClickEvent event) {
                    _connect.setEnabled(false);
                    _subProtocol.setEnabled(false);
                    if (Boolean.TRUE == _subProtocol.getValue()) {
                        webSocket.connect(getWebSocketURL(), "superchat");
                    } else {
                        webSocket.connect(getWebSocketURL());
                    }
                }
            });
            _disconnect = new Button("Disconnect", new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    webSocket.close();
                    _disconnect.setEnabled(false);
                }
            });
            _disconnect.setEnabled(false);
            _send = new Button("Send", new ClickHandler() {
                @Override
                public void onClick(ClickEvent event) {
                    send(webSocket, input.getValue(), Boolean.TRUE == checkBox.getValue());
                }
            });
            _send.setEnabled(false);
            _messages = new HTML();
            _scrollPanel = new ScrollPanel();
            _scrollPanel.setHeight("250px");
            _scrollPanel.add(_messages);
            
            Panel panel = new VerticalPanel();
            panel.setHeight("260px"); 
            
            RootPanel.get().add(panel);
            RootPanel.get().add(_scrollPanel);            
            {
                final FlowPanel controls = new FlowPanel();
                controls.add(_connect);
                controls.add(_disconnect);
                controls.add(_subProtocol);
                RootPanel.get().add(controls);
            }
            {
                final FlowPanel controls = new FlowPanel();
                controls.add(input);
                controls.add(checkBox);
                controls.add(_send);
                RootPanel.get().add(controls);
            }
        }
    }

    /**
     * 
     * @return 
     */
    private String getWebSocketURL() {
        final String moduleBaseURL = GWT.getHostPageBaseURL();
        return moduleBaseURL.replaceFirst("^http\\:", "ws:") + "chat";
        //return moduleBaseURL.replaceFirst("^http\\:", "ws:") + "WebSocketServlet";
        //  String webSocketUrl = "ws://localhost:8080/SenchaGXT3/Main/WebSocketServlet";
    }

    /**
     * 
     * @param webSocket
     * @param message
     * @param binary 
     */
    private void send(final WebSocket webSocket, final String message, final boolean binary) {
        if (binary) {
            final Int8Array arrayBuffer8 = TypedArrays.createInt8Array(message.length());
            arrayBuffer8.set(message.getBytes());
            webSocket.send(arrayBuffer8);
        } else {
            webSocket.send(message.toString());
        }
        
//        webSocket.send(message);
    }

//    public void onMessage(@Nonnull final WebSocket webSocket, @Nonnull final ArrayBuffer data) {
//        logStatus("Message", webSocket);
//        final Int8Array arrayBuffer = TypedArrays.createInt8Array(data);
//        final StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < arrayBuffer.length(); i++) {
//            sb.append((char) arrayBuffer.get(i));
//        }
//        appendText("binary message: " + sb, "black");
//    }

    @Override
    public void onMessage(@Nonnull final WebSocket webSocket, @Nonnull final String textData) {
        logStatus("Message", webSocket);
        appendText("message: " + textData, "black");
    }

    @Override
    public void onError(@Nonnull final WebSocket webSocket) {
        logStatus("Error", webSocket);
        appendText("error", "red");
        _connect.setEnabled(false);
        _subProtocol.setEnabled(false);
        _disconnect.setEnabled(false);
        _send.setEnabled(false);
    }

    @Override
    public void onClose(@Nonnull final WebSocket webSocket,
            final boolean wasClean,
            final int code,
            @Nullable final String reason) {
        logStatus("Close", webSocket);
        appendText("close", "silver");
        _connect.setEnabled(true);
        _subProtocol.setEnabled(true);
        _disconnect.setEnabled(false);
        _send.setEnabled(false);
    }

    public void onOpen(@Nonnull final WebSocket webSocket) {
        logStatus("Open", webSocket);
        appendText("open", "silver");
        _disconnect.setEnabled(true);
        _send.setEnabled(true);
    }

    private void logStatus(@Nonnull final String section,
            @Nonnull final WebSocket webSocket) {
        final String suffix = !webSocket.isConnected()
                ? ""
                : "URL:" + webSocket.getURL() + "\n"
                + "BinaryType:" + webSocket.getBinaryType() + "\n"
                + "BufferedAmount:" + webSocket.getBufferedAmount() + "\n"
                + "Extensions:" + webSocket.getExtensions() + "\n"
                + "Protocol:" + webSocket.getProtocol();
        LOG.warning("WebSocket @ " + section + "\n" + "ReadyState:" + webSocket.getReadyState() + "\n" + suffix);
    }

    private void appendText(final String text, final String color) {
        final DivElement div = Document.get().createDivElement();
        div.setInnerText(text);
        div.setAttribute("style", "color:" + color);
        _messages.getElement().appendChild(div);
        _scrollPanel.scrollToBottom();
    }
}

También te podría gustar...

Deja un comentario