Rewrite StompClient to use a different WebSocket client implementation

This commit is contained in:
Andrejs Mivreņiks 2017-11-27 22:02:56 +02:00
parent c0664f1927
commit 9fca342a86
10 changed files with 313 additions and 250 deletions

View File

@ -4,11 +4,14 @@ This is a [STOMP](http://eu.mivrenik.stomp.github.io/) protocol implementation.
## Example backend using Spring Boot ## Example backend using Spring Boot
The following example is taken from Spring's ["Using WebSocket to build an interactive web application"](https://spring.io/guides/gs/messaging-stomp-websocket/) guide but with SockJS disabled.
### Configuration ### Configuration
```java ```java
@Configuration @Configuration
public class WebSocketMessageBrokerConfigurer extends AbstractWebSocketMessageBrokerConfigurer { @EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override @Override
public void configureMessageBroker(MessageBrokerRegistry config) { public void configureMessageBroker(MessageBrokerRegistry config) {
@ -18,7 +21,7 @@ public class WebSocketMessageBrokerConfigurer extends AbstractWebSocketMessageBr
@Override @Override
public void registerStompEndpoints(StompEndpointRegistry registry) { public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/hello"); registry.addEndpoint("/gs-guide-websocket");
} }
} }
``` ```
@ -31,38 +34,47 @@ public class GreetingController {
@MessageMapping("/hello") @MessageMapping("/hello")
@SendTo("/topic/greetings") @SendTo("/topic/greetings")
public String greeting(String message) throws Exception { public Greeting greeting(HelloMessage message) throws Exception {
return "Hello, " + message + "!"; Thread.sleep(1000); // simulated delay
return new Greeting("Hello, " + message.getName() + "!");
} }
} }
``` ```
## Usage ## Usage
See the included client [example module](example).
```java ```java
StompClient stompClient; final StompClient stompSocket = new StompClient(URI.create("ws://localhost:8080/gs-guide-websocket"));
// Wait for a connection to establish
boolean connected;
try { try {
stompClient = new StompClient("ws://localhost:7777/hello"); connected = stompSocket.connectBlocking();
stompClient.connect(); } catch (InterruptedException e) {
} catch (WebSocketException | IOException e) {
e.printStackTrace(); e.printStackTrace();
return; return;
} }
if (!connected) {
System.out.println("Failed to connect to the socket");
return;
}
// Subscribing to a topic // Subscribing to a topic
stompClient.subscribe("/topic/greetings", new StompMessageListener() { stompSocket.subscribe("/topic/greetings", new StompMessageListener() {
@Override @Override
public void onMessage(String message) { public void onMessage(String message) {
System.out.println("Server message: " + message); System.out.println("Server message: " + message);
// Disconnect
stompSocket.close();
} }
}); });
// Sending JSON message to a server // Sending JSON message to a server
String message = "Jack"; String message = "{\"name\": \"Jack\"}";
stompClient.send("/app/hello", message); stompSocket.send("/app/hello", message);
// ...
// Disconnect at some point
// stompClient.disconnect();
``` ```

View File

@ -3,7 +3,7 @@ version '0.1'
apply plugin: 'java' apply plugin: 'java'
sourceCompatibility = 1.8 sourceCompatibility = 1.7
repositories { repositories {
mavenCentral() mavenCentral()

View File

@ -1,34 +1,43 @@
package eu.mivrenik.stomp.example; package eu.mivrenik.stomp.example;
import com.neovisionaries.ws.client.WebSocketException; import eu.mivrenik.stomp.StompFrame;
import eu.mivrenik.stomp.StompMessageListener;
import eu.mivrenik.stomp.client.StompClient; import eu.mivrenik.stomp.client.StompClient;
import eu.mivrenik.stomp.client.listener.StompMessageListener;
import java.io.IOException; import java.net.URI;
public class StompClientExample { public class StompClientExample {
public static void main(String[] args) { public static void main(String[] args) {
StompClient stompClient; final StompClient stompSocket = new StompClient(URI.create("ws://localhost:8080/gs-guide-websocket"));
// Wait for a connection to establish
boolean connected;
try { try {
stompClient = new StompClient("ws://localhost:7777/hello"); connected = stompSocket.connectBlocking();
stompClient.connect(); } catch (InterruptedException e) {
} catch (WebSocketException | IOException e) {
e.printStackTrace(); e.printStackTrace();
return; return;
} }
if (!connected) {
System.out.println("Failed to connect to the socket");
return;
}
// Subscribing to a topic // Subscribing to a topic once STOMP connection is established
stompClient.subscribe("/topic/greetings", new StompMessageListener() { stompSocket.subscribe("/topic/greetings", new StompMessageListener() {
@Override @Override
public void onMessage(String message) { public void onMessage(StompFrame stompFrame) {
System.out.println("Server message: " + message); System.out.println("Server message: " + stompFrame.getBody());
// Disconnect
stompSocket.close();
} }
}); });
// Sending JSON message to a server // Sending JSON message to a server
String message = "Jack"; String message = "{\"name\": \"Jack\"}";
stompClient.send("/app/hello", message); stompSocket.send("/app/hello", message);
} }
} }

View File

@ -3,7 +3,7 @@ version '0.1'
apply plugin: 'java' apply plugin: 'java'
sourceCompatibility = 1.8 sourceCompatibility = 1.7
repositories { repositories {
mavenCentral() mavenCentral()
@ -11,5 +11,5 @@ repositories {
dependencies { dependencies {
compile project(':stomp') compile project(':stomp')
compile 'com.neovisionaries:nv-websocket-client:1.30' compile 'org.java-websocket:Java-WebSocket:1.3.6'
} }

View File

@ -21,220 +21,97 @@
*/ */
package eu.mivrenik.stomp.client; package eu.mivrenik.stomp.client;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketException;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;
import com.neovisionaries.ws.client.WebSocketListener;
import com.neovisionaries.ws.client.WebSocketState;
import eu.mivrenik.stomp.StompCommand; import eu.mivrenik.stomp.StompCommand;
import eu.mivrenik.stomp.StompFrame; import eu.mivrenik.stomp.StompFrame;
import eu.mivrenik.stomp.StompHeader; import eu.mivrenik.stomp.StompHeader;
import eu.mivrenik.stomp.StompMessageListener; import eu.mivrenik.stomp.client.listener.StompConnectionListener;
import eu.mivrenik.stomp.StompSubscription; import eu.mivrenik.stomp.client.listener.StompMessageListener;
import org.java_websocket.WebSocketListener;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import java.io.IOException; import java.io.IOException;
import java.net.URI;
import java.util.HashMap; import java.util.HashMap;
import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.UUID; import java.util.UUID;
/** /**
* STOMP v1.2 client using `nv-websocket-client` WebSocket client * STOMP v1.2 client using `Java-WebSocket` WebSocket client implementation.
* implementation. * <p>
* * {@see https://eu.mivrenik.stomp.github.io/eu.mivrenik.stomp-specification-1.2.html}
* @see https://eu.mivrenik.stomp.github.io/eu.mivrenik.stomp-specification-1.2.html * {@see https://github.com/TooTallNate/Java-WebSocket}
* @see https://github.com/TakahikoKawasaki/nv-websocket-client */
public class StompClient extends WebSocketClient {
/**
* Current STOMP implementation version.
*/ */
public class StompClient {
private static final String STOMP_VERSION = "1.2"; private static final String STOMP_VERSION = "1.2";
private final Map<Integer, StompSubscription> subscriptions = new HashMap<>();
private WebSocket webSocket; /**
* STOMP topic subscription listeners.
*/
private Map<Integer, StompSubscription> subscriptions = new HashMap<>();
/**
* STOMP connection status.
*/
private boolean stompConnected; private boolean stompConnected;
public StompClient(String url) throws IOException { /**
this.webSocket = new WebSocketFactory().createSocket(url); * STOMP connection listener.
this.webSocket.addListener(webSocketListener); */
private StompConnectionListener stompConnectionListener;
/**
* {@inheritDoc}
*/
public StompClient(URI serverUri) {
super(serverUri);
} }
public void connect() throws WebSocketException, IOException { /**
if (webSocket.getState() != WebSocketState.CREATED) { * {@inheritDoc}
webSocket = webSocket.recreate(); */
public StompClient(URI serverUri, Draft protocolDraft) {
super(serverUri, protocolDraft);
} }
webSocket.connect();
/**
* {@inheritDoc}
*/
public StompClient(URI serverUri, Draft protocolDraft, Map<String, String> httpHeaders, int connectTimeout) {
super(serverUri, protocolDraft, httpHeaders, connectTimeout);
}
@Override
public void onOpen(ServerHandshake handshakedata) {
connectStomp(); connectStomp();
} }
protected void connectStomp() {
if (stompConnected) {
return;
}
Map<String, String> headers = new HashMap<>();
headers.put(StompHeader.ACCEPT_VERSION.toString(), STOMP_VERSION);
headers.put(StompHeader.HOST.toString(), webSocket.getURI().getHost());
webSocket.sendText(new StompFrame(StompCommand.CONNECT, headers).toString());
}
public void disconnect() {
disconnectStomp();
webSocket.disconnect();
}
protected void disconnectStomp() {
if (!stompConnected) {
return;
}
webSocket.sendText(new StompFrame(StompCommand.DISCONNECT).toString());
}
public boolean isConnected() {
return stompConnected;
}
public void send(String destination, String message) {
send(destination, message, null);
}
public void send(String destination, String message, Map<String, String> headers) {
if (headers == null) {
headers = new HashMap<>();
}
headers.put(StompHeader.DESTINATION.toString(), destination);
webSocket.sendText(new StompFrame(StompCommand.SEND, headers, message).toString());
}
public StompSubscription subscribe(String destination, StompMessageListener listener) {
StompSubscription subscription = new StompSubscription(UUID.randomUUID().hashCode(), destination, listener);
Map<String, String> headers = new HashMap<>();
headers.put(StompHeader.ID.toString(), String.valueOf(subscription.getId()));
headers.put(StompHeader.DESTINATION.toString(), subscription.getDestination());
webSocket.sendText(new StompFrame(StompCommand.SUBSCRIBE, headers).toString());
subscriptions.put(subscription.getId(), subscription);
return subscription;
}
public void unsubscribe(StompSubscription subscription) {
Map<String, String> headers = new HashMap<>();
headers.put(StompHeader.ID.toString(), String.valueOf(subscription.getId()));
webSocket.sendText(new StompFrame(StompCommand.UNSUBSCRIBE, headers).toString());
subscriptions.remove(subscription.getId());
}
public void unsubscribeAll(String destination) {
for (StompSubscription s : subscriptions.values()) {
if (s.getDestination().equals(destination)) {
unsubscribe(s);
}
}
}
private final WebSocketListener webSocketListener = new WebSocketListener() {
@Override @Override
public void handleCallbackError(WebSocket websocket, Throwable cause) throws Exception { public void onMessage(String message) {
} StompFrame stompFrame = StompFrame.fromString(message);
@Override
public void onBinaryFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onBinaryMessage(WebSocket websocket, byte[] binary) throws Exception {
}
@Override
public void onCloseFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers) throws Exception {
}
@Override
public void onConnectError(WebSocket websocket, WebSocketException cause) throws Exception {
}
@Override
public void onContinuationFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame,
WebSocketFrame clientCloseFrame, boolean closedByServer) throws Exception {
stompConnected = false;
}
@Override
public void onError(WebSocket websocket, WebSocketException cause) throws Exception {
}
@Override
public void onFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onFrameError(WebSocket websocket, WebSocketException cause, WebSocketFrame frame)
throws Exception {
}
@Override
public void onFrameSent(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onFrameUnsent(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onMessageDecompressionError(WebSocket websocket, WebSocketException cause, byte[] compressed)
throws Exception {
}
@Override
public void onMessageError(WebSocket websocket, WebSocketException cause, List<WebSocketFrame> frames)
throws Exception {
}
@Override
public void onPingFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onPongFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onSendError(WebSocket websocket, WebSocketException cause, WebSocketFrame frame)
throws Exception {
}
@Override
public void onSendingFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
}
@Override
public void onSendingHandshake(WebSocket websocket, String requestLine, List<String[]> headers)
throws Exception {
}
@Override
public void onStateChanged(WebSocket websocket, WebSocketState newState) throws Exception {
}
@Override
public void onTextFrame(WebSocket websocket, WebSocketFrame frame) throws Exception {
StompFrame stompFrame = StompFrame.fromString(frame.getPayloadText());
switch (stompFrame.getCommand()) { switch (stompFrame.getCommand()) {
case CONNECTED: case CONNECTED:
stompConnected = true; stompConnected = true;
if (stompConnectionListener != null) {
stompConnectionListener.onConnected();
}
break; break;
case MESSAGE: case MESSAGE:
Integer subscriptionId = Integer Integer subscriptionId = Integer.valueOf(
.valueOf(stompFrame.getHeaders().get(StompHeader.SUBSCRIPTION.toString())); stompFrame.getHeaders().get(StompHeader.SUBSCRIPTION.toString())
);
subscriptions.get(subscriptionId).getListener().onMessage(stompFrame.getBody()); subscriptions.get(subscriptionId).getListener().onMessage(stompFrame);
break;
case DISCONNECT:
stompConnected = false;
if (stompConnectionListener != null) {
stompConnectionListener.onDisconnected();
}
break; break;
default: default:
break; break;
@ -242,16 +119,140 @@ public class StompClient {
} }
@Override @Override
public void onTextMessage(WebSocket websocket, String text) throws Exception { public void onClose(int code, String reason, boolean remote) {
stompConnected = false;
if (stompConnectionListener != null) {
stompConnectionListener.onDisconnected();
}
} }
@Override @Override
public void onTextMessageError(WebSocket websocket, WebSocketException cause, byte[] data) public void onError(Exception ex) {
throws Exception { ex.printStackTrace();
} }
@Override /**
public void onUnexpectedError(WebSocket websocket, WebSocketException cause) throws Exception { * Create STOMP connection.
*/
protected void connectStomp() {
if (stompConnected) {
return;
}
if (stompConnectionListener != null) {
stompConnectionListener.onConnecting();
}
Map<String, String> headers = new HashMap<>();
headers.put(StompHeader.ACCEPT_VERSION.toString(), STOMP_VERSION);
headers.put(StompHeader.HOST.toString(), uri.getHost());
send(new StompFrame(StompCommand.CONNECT, headers).toString());
}
/**
* Disconnect STOMP.
*/
protected void disconnectStomp() {
if (!stompConnected) {
return;
}
send(new StompFrame(StompCommand.DISCONNECT).toString());
}
/**
* Send text message to the server.
*
* @param destination destination
* @param message text message
*/
public void send(String destination, String message) {
send(destination, message, null);
}
/**
* Send text message to the server.
*
* @param destination destination
* @param message text message
* @param headers (optional) additional headers
*/
public void send(String destination, String message, Map<String, String> headers) {
if (headers == null) {
headers = new HashMap<>();
}
headers.put(StompHeader.DESTINATION.toString(), destination);
StompFrame frame = new StompFrame(StompCommand.SEND, headers, message);
send(frame.toString());
}
/**
* Subscribe to a specific topic.
*
* @param destination topic destination
* @param listener listener
* @return STOMP subscription data that can be used to unsubscribe
*/
public StompSubscription subscribe(String destination, StompMessageListener listener) {
StompSubscription subscription = new StompSubscription(UUID.randomUUID().hashCode(), destination, listener);
Map<String, String> headers = new HashMap<>();
headers.put(StompHeader.ID.toString(), String.valueOf(subscription.getId()));
headers.put(StompHeader.DESTINATION.toString(), subscription.getDestination());
StompFrame frame = new StompFrame(StompCommand.SUBSCRIBE, headers);
send(frame.toString());
subscriptions.put(subscription.getId(), subscription);
return subscription;
}
/**
* Remove a single subscription.
*
* @param subscription subscription
*/
public void removeSubscription(StompSubscription subscription) {
Map<String, String> headers = new HashMap<>();
headers.put(StompHeader.ID.toString(), String.valueOf(subscription.getId()));
StompFrame frame = new StompFrame(StompCommand.UNSUBSCRIBE, headers);
send(frame.toString());
subscriptions.remove(subscription.getId());
}
/**
* Unsubscribe all from a single topic.
*
* @param destination topic
*/
public void removeAllSubscriptions(String destination) {
for (StompSubscription s : subscriptions.values()) {
if (s.getDestination().equals(destination)) {
removeSubscription(s);
}
}
}
/**
* Check if STOMP is currently connected.
*
* @return STOMP connection status
*/
public boolean isStompConnected() {
return stompConnected;
}
/**
* Register STOMP conection listener.
*
* @param stompConnectionListener listener
*/
public void setStompConnectionListener(StompConnectionListener stompConnectionListener) {
this.stompConnectionListener = stompConnectionListener;
} }
};
} }

View File

@ -19,7 +19,9 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE. * SOFTWARE.
*/ */
package eu.mivrenik.stomp; package eu.mivrenik.stomp.client;
import eu.mivrenik.stomp.client.listener.StompMessageListener;
/** /**
* STOMP subscription POJO * STOMP subscription POJO

View File

@ -0,0 +1,25 @@
package eu.mivrenik.stomp.client.listener;
/**
* STOMP connection established listener.
*/
public abstract class StompConnectionListener {
/**
* STOMP is in establishing connection state.
*/
public void onConnecting() {
}
/**
* STOMP has been successfully connected.
*/
public void onConnected() {
}
/**
* STOMP has been disconnected.
*/
public void onDisconnected() {
}
}

View File

@ -19,11 +19,19 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE. * SOFTWARE.
*/ */
package eu.mivrenik.stomp; package eu.mivrenik.stomp.client.listener;
import eu.mivrenik.stomp.StompFrame;
/** /**
* STOMP message subscription listener interface. * STOMP message subscription listener interface.
*/ */
public interface StompMessageListener { public interface StompMessageListener {
void onMessage(String message);
/**
* Subscription message received callback.
*
* @param stompFrame STOMP message frame
*/
void onMessage(StompFrame stompFrame);
} }

View File

@ -3,7 +3,7 @@ version '0.1'
apply plugin: 'java' apply plugin: 'java'
sourceCompatibility = 1.8 sourceCompatibility = 1.7
repositories { repositories {
mavenCentral() mavenCentral()

View File

@ -34,37 +34,12 @@ public class StompFrame {
private Map<String, String> headers = new HashMap<>(); private Map<String, String> headers = new HashMap<>();
private String body; private String body;
public StompFrame(StompCommand command) { /**
this(command, null, null); * Create frame from string.
} *
* @param data Data string
public StompFrame(StompCommand command, Map<String, String> headers) { * @return STOMP frame instance
this(command, headers, null); */
}
public StompFrame(StompCommand command, Map<String, String> headers, String body) {
this.command = command;
this.body = body;
if (headers != null) {
for (String k : headers.keySet()) {
this.headers.put(k, headers.get(k));
}
}
}
public StompCommand getCommand() {
return command;
}
public Map<String, String> getHeaders() {
return headers;
}
public String getBody() {
return body;
}
public static StompFrame fromString(String data) { public static StompFrame fromString(String data) {
String[] lines = data.split("\n"); String[] lines = data.split("\n");
int pos = 0; int pos = 0;
@ -99,6 +74,37 @@ public class StompFrame {
return new StompFrame(command, headers, body.toString()); return new StompFrame(command, headers, body.toString());
} }
public StompFrame(StompCommand command) {
this(command, null, null);
}
public StompFrame(StompCommand command, Map<String, String> headers) {
this(command, headers, null);
}
public StompFrame(StompCommand command, Map<String, String> headers, String body) {
this.command = command;
this.body = body;
if (headers != null) {
for (String k : headers.keySet()) {
this.headers.put(k, headers.get(k));
}
}
}
public StompCommand getCommand() {
return command;
}
public Map<String, String> getHeaders() {
return headers;
}
public String getBody() {
return body;
}
@Override @Override
public String toString() { public String toString() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();