MG Websocket - mrkcsc/android-mg-bootstrap GitHub Wiki

Configuration

Setting up the socket:


// Initialize a web socket.
websocket =  MGWebsocket.create();

// Provide it a url - required.
websocket.getConfig().setUrl("ws://10.0.1.11:3001");

// Should messages buffer - optional.
websocket.getConfig().setBuffered(true);

// Time to reconnect, default is ten seconds and
// a null can be provided to disable reconnect.
websocket.getConfig().setReconnectDelay(1000);

Usage

Connecting and disconnecting:


// Open socket.
websocket.connect();

// Close socket.
websocket.disconnect();

Sending messages to the socket:


// You can send a complex object to be serialized.
websocket.message(new ComplexObject());

// Or just a string.
websocket.message("test");

Getting Web Socket state:


// Fetch the state.
MGWebsocketState state = websocket.getState();

// Supported states.
public enum MGWebsocketState {

    NOT_YET_CONNECTED, CONNECTING, OPEN, CLOSING, CLOSED
}

Listening for events:


// Listen for messages.
websocket.onMessage().subscribe(message -> { });

// Listen for open event.
websocket.onOpened().subscribe(opened -> { });

// Listen for close event.
websocket.onClosed().subscribe(closed -> { });

// Listen for error event.
websocket.onError().subscribe(error -> { });

Configuring the heartbeat:


// Heartbeat allows you to keep web web socket alive, 
// first parameter is the interval, second is message.
websocket.heartBeat(10000, "ping");