When folks hear WebSocket, they most-likely imaging using the (native) JavaScript APIs, from modern browsers, to access a WebSocket server. However there is a need for other platforms, like a regular Java client. Several Http Client projects, like Async Http Client or Apache’s HttpClient , have already plans to add WebSocket support.
The Kaazing WebSocket Gateway is an advanced WebSocket server, which contains several Client SDKs, including a Java-based WebSocket client!
After downloading and extracting the Kaazing WebSocket Gateway, you find the Java API inside the lib/client/java folder. Add the JAR to a (blank) Java Project in your IDE (e.g. Eclipse).
A pretty quick (and simple) test is using the API against the public Echo-Server, hosted at websocket.org,like:
package net.wessendorf.kaazing.gateway;
import java.net.URI;
import com.kaazing.gateway.client.html5.WebSocket;
import com.kaazing.gateway.client.html5.WebSocketAdapter;
import com.kaazing.gateway.client.html5.WebSocketEvent;
public class WebSocketTest {
public static void main(String[] args) throws Exception {
final WebSocket ws = new WebSocket();
ws.addWebSocketListener(
new WebSocketAdapter() {
@Override
public void onMessage(WebSocketEvent messageEvent) {
System.out.println("Received Event Data: " + messageEvent.getData());
// let's close the open connection...
try {
ws.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onOpen(WebSocketEvent openEvent) {
System.out.println("Connection to Server is up!");
// we are able to talk to the WebSocket gateway
try {
ws.send("Hey, server!");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
);
ws.connect(new URI("ws://echo.websocket.org:80"));
}
}
The Java code is pretty straightforward: It creates a WebSocket object, overrides a convenience class to react on some WebSocket events and finally connects to the actual Echo-Server.
Once the connection is up (inside the onOpen() callback), we are sending a simple text to the server. The server returns exactly the same string back to the sending client. This issues our onMessage() callback. After printing the received data to the console, we close the open connection.
Instead of using the remote server, you could try the demos on your machine, by installing the Kaazing WebSocket Gateway on your box!
Have fun!