我创建了一个小的java swing应用程序,我想使用WebSocket将数据从服务器传输到客户端。有人可以给我一步一步说明如何做到这一点吗?我正在使用 JBoss应用服务器。
答案 0 :(得分:2)
一种方法是使用Jetty WebSocket Client API,跳转你已经实现了Server Side Web Socket
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();
}
}
}
}