com.googlecode.gwtrpcplus.client.util.websocket.WebSocket Maven / Gradle / Ivy
package com.googlecode.gwtrpcplus.client.util.websocket;
import com.google.gwt.core.client.GWT;
public class WebSocket {
public static interface Callback {
void onOpen();
void onClose();
void onError(Object e);
void onMessage(String message);
}
private final Callback callback;
private Object ws;
public WebSocket(Callback callback) {
this.callback = callback;
}
private boolean isConnected=false;
private final void onopen() {
isConnected=true;
try{
callback.onOpen();
}catch (Throwable e) {
if(GWT.getUncaughtExceptionHandler()!=null)
GWT.getUncaughtExceptionHandler().onUncaughtException(e);
else
GWT.log("Error",e);
}
}
private final void onclose() {
isConnected=false;
ws=null;
try{
callback.onClose();
}catch (Throwable e) {
if(GWT.getUncaughtExceptionHandler()!=null)
GWT.getUncaughtExceptionHandler().onUncaughtException(e);
else
GWT.log("Error",e);
}
}
private final void onmessage(String message) {
try{
callback.onMessage(message);
}catch (Throwable e) {
if(GWT.getUncaughtExceptionHandler()!=null)
GWT.getUncaughtExceptionHandler().onUncaughtException(e);
else
GWT.log("Error",e);
}
}
private final void onerror(Object error) {
try{
callback.onError(error);
}catch (Throwable e) {
if(GWT.getUncaughtExceptionHandler()!=null)
GWT.getUncaughtExceptionHandler().onUncaughtException(e);
else
GWT.log("Error",e);
}
}
public static native boolean isSupported()/*-{
return "WebSocket" in $wnd || "MozWebSocket" in $wnd;
}-*/;
public boolean isConnected(){
return isSupported() && isConnected;
}
public native void connect(String serverUrl) /*-{
var that = this;
if("WebSocket" in $wnd)
[email protected]::ws = new WebSocket(serverUrl);
else
[email protected]::ws = new MozWebSocket(serverUrl);
[email protected]::ws.onopen = function() {
[email protected]::onopen()();
};
[email protected]::ws.onmessage = function(response) {
if (response.data) {
[email protected]::onmessage(Ljava/lang/String;)( response.data );
}
};
[email protected]::ws.onclose = function(m) {
[email protected]::onclose()();
};
[email protected]::ws.onerror = function(m) {
[email protected]::onerror(Ljava/lang/Object;)(m);
};
}-*/;
public native void send(String message) /*-{
if ([email protected]::ws) {
[email protected]::ws.send(message);
} else {
alert("not connected!" + [email protected]::ws);
}
}-*/;
public native void close() /*-{
[email protected]::ws.close();
}-*/;
}