Search code examples
javawebsocketjava-ee-6java-ee-7

Implementing WebSocket in Java Swing Application


I created a small java swing application and I want to use WebSocket for the transferring of data from the server to the client. Can someone give me a step by step instructions on how to do it? I'm using JBoss application server.


Solution

  • One Approach is to use Jetty WebSocket Client API, Hopping that you already implemented Server Side Web Socket

    Tutorial

    Maven Dependency org.eclipse.jetty.websocket websocket-client ${project.version}

      package examples;
    
     import java.net.URI;
     import java.util.concurrent.TimeUnit;
     import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
     import org.eclipse.jetty.websocket.client.WebSocketClient;
    
     public class SimpleEchoClient {
    
    public static void main(String[] args) {
        String destUri = "ws://echo.websocket.org";
        if (args.length > 0) {
            destUri = args[0];
        }
        WebSocketClient client = new WebSocketClient();
        SimpleEchoSocket socket = new SimpleEchoSocket();
        try {
            client.start();
            URI echoUri = new URI(destUri);
            ClientUpgradeRequest request = new ClientUpgradeRequest();
            client.connect(socket, echoUri, request);
            System.out.printf("Connecting to : %s%n", echoUri);
            socket.awaitClose(5, TimeUnit.SECONDS);
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            try {
                client.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    }