在Java Swing应用程序中实现WebSocket

时间:2015-05-08 09:13:32

标签: java websocket java-ee-6 java-ee-7

我创建了一个小的java swing应用程序,我想使用WebSocket将数据从服务器传输到客户端。有人可以给我一步一步说明如何做到这一点吗?我正在使用 JBoss应用服务器

1 个答案:

答案 0 :(得分:2)

一种方法是使用Jetty WebSocket Client API,跳转你已经实现了Server Side Web Socket

Tutorial

Maven依赖                   org.eclipse.jetty.websocket            WebSocket的客户端            $ {} 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();
        }
    }
}
}