You can, of course, use WebSockets from a Java desktop application, outside of a sandboxed browser program. The idea is that you can create thick clients that create TCP connections, so of course they should be able to create WebSocket connections on top of these TCP connections.
One of the newest and best APIs for this is written by Kaazing, in terms of the fact that WebSocket is similar to a socket and can be created using simple URI files ws: //.
The API is discussed in detail on the Kaazing Gateway 5.0 Java WebSocket documentation website . You can download a simple gateway from Kaazing here.
Create a website:
import com.kaazing.net.ws.WebSocket; import com.kaazing.net.ws.WebSocketFactory; wsFactory = WebSocketFactory.createWebSocketFactory(); ws = wsFactory.createWebSocket(URI.create("ws://example.com:8001/path")); ws.connect(); // This will block or throw an exception if failed.
To send messages, add a WebSocketMessageWriter object:
WebSocketMessageWriter writer = ws.getMessageWriter(); String text = "Hello WebSocket!"; writer.writeText(text);
To receive or consume messages, add WebSocket and WebSocketMessageReader objects:
wsFactory = WebSocketFactory.createWebSocketFactory(); ws = wsFactory.createWebSocket(URI.create("ws://example.com:8001/path")); ws.connect(); // This will block or throw an exception if failed. WebSocketMessageReader reader = ws.getMessageReader(); WebSocketMessageType type = null; // Block till a message arrives // Loop till the connection goes away while ((type = reader.next()) != WebSocketMessageType.EOS) { switch (type) { // Handle both text and binary messages case TEXT: CharSequence text = reader.getText(); log("RECEIVED TEXT MESSAGE: " + text.toString()); break; case BINARY: ByteBuffer buffer = reader.getBinary(); log("RECEIVED BINARY MESSAGE: " + getHexDump(buffer)); break; } }
(Full disclosure: I worked at Kaazing Corporation as a server engineer.)
nowucca
source share