move package name
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
package io.socket.engineio.client;
|
||||
|
||||
public class EngineIOException extends Exception {
|
||||
|
||||
public String transport;
|
||||
public Object code;
|
||||
|
||||
public EngineIOException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public EngineIOException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public EngineIOException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
|
||||
public EngineIOException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
}
|
||||
32
src/main/java/io/socket/engineio/client/HandshakeData.java
Normal file
32
src/main/java/io/socket/engineio/client/HandshakeData.java
Normal file
@@ -0,0 +1,32 @@
|
||||
package io.socket.engineio.client;
|
||||
|
||||
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
public class HandshakeData {
|
||||
|
||||
public String sid;
|
||||
public String[] upgrades;
|
||||
public long pingInterval;
|
||||
public long pingTimeout;
|
||||
|
||||
/*package*/ HandshakeData(String data) throws JSONException {
|
||||
this(new JSONObject(data));
|
||||
}
|
||||
|
||||
/*package*/ HandshakeData(JSONObject data) throws JSONException {
|
||||
JSONArray upgrades = data.getJSONArray("upgrades");
|
||||
int length = upgrades.length();
|
||||
String[] _upgrades = new String[length];
|
||||
for (int i = 0; i < length; i ++) {
|
||||
_upgrades[i] = upgrades.getString(i);
|
||||
}
|
||||
|
||||
this.sid = data.getString("sid");
|
||||
this.upgrades = _upgrades;
|
||||
this.pingInterval = data.getLong("pingInterval");
|
||||
this.pingTimeout = data.getLong("pingTimeout");
|
||||
}
|
||||
}
|
||||
876
src/main/java/io/socket/engineio/client/Socket.java
Normal file
876
src/main/java/io/socket/engineio/client/Socket.java
Normal file
@@ -0,0 +1,876 @@
|
||||
package io.socket.engineio.client;
|
||||
|
||||
import io.socket.emitter.Emitter;
|
||||
import io.socket.engineio.client.transports.Polling;
|
||||
import io.socket.engineio.client.transports.PollingXHR;
|
||||
import io.socket.engineio.client.transports.WebSocket;
|
||||
import io.socket.engineio.parser.Packet;
|
||||
import io.socket.engineio.parser.Parser;
|
||||
import io.socket.parseqs.ParseQS;
|
||||
import io.socket.thread.EventThread;
|
||||
import org.json.JSONException;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.Future;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
|
||||
/**
|
||||
* The socket class for Event.IO Client.
|
||||
*
|
||||
* @see <a href="https://github.com/LearnBoost/engine.io-client">https://github.com/LearnBoost/engine.io-client</a>
|
||||
*/
|
||||
public class Socket extends Emitter {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(Socket.class.getName());
|
||||
|
||||
private enum ReadyState {
|
||||
OPENING, OPEN, CLOSING, CLOSED;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString().toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Called on successful connection.
|
||||
*/
|
||||
public static final String EVENT_OPEN = "open";
|
||||
|
||||
/**
|
||||
* Called on disconnection.
|
||||
*/
|
||||
public static final String EVENT_CLOSE = "close";
|
||||
|
||||
/**
|
||||
* Called when data is received from the server.
|
||||
*/
|
||||
public static final String EVENT_MESSAGE = "message";
|
||||
|
||||
/**
|
||||
* Called when an error occurs.
|
||||
*/
|
||||
public static final String EVENT_ERROR = "error";
|
||||
|
||||
public static final String EVENT_UPGRADE_ERROR = "upgradeError";
|
||||
|
||||
/**
|
||||
* Called on completing a buffer flush.
|
||||
*/
|
||||
public static final String EVENT_FLUSH = "flush";
|
||||
|
||||
/**
|
||||
* Called after `drain` event of transport if writeBuffer is empty.
|
||||
*/
|
||||
public static final String EVENT_DRAIN = "drain";
|
||||
|
||||
public static final String EVENT_HANDSHAKE = "handshake";
|
||||
public static final String EVENT_UPGRADING = "upgrading";
|
||||
public static final String EVENT_UPGRADE = "upgrade";
|
||||
public static final String EVENT_PACKET = "packet";
|
||||
public static final String EVENT_PACKET_CREATE = "packetCreate";
|
||||
public static final String EVENT_HEARTBEAT = "heartbeat";
|
||||
public static final String EVENT_DATA = "data";
|
||||
|
||||
/**
|
||||
* Called on a new transport is created.
|
||||
*/
|
||||
public static final String EVENT_TRANSPORT = "transport";
|
||||
|
||||
private static final Runnable noop = new Runnable() {
|
||||
@Override
|
||||
public void run() {}
|
||||
};
|
||||
|
||||
/**
|
||||
* The protocol version.
|
||||
*/
|
||||
public static final int protocol = Parser.protocol;
|
||||
|
||||
private static boolean priorWebsocketSuccess = false;
|
||||
|
||||
private static SSLContext defaultSSLContext;
|
||||
private static HostnameVerifier defaultHostnameVerifier;
|
||||
|
||||
private boolean secure;
|
||||
private boolean upgrade;
|
||||
private boolean timestampRequests;
|
||||
private boolean upgrading;
|
||||
private boolean rememberUpgrade;
|
||||
/*package*/ int port;
|
||||
private int policyPort;
|
||||
private int prevBufferLen;
|
||||
private long pingInterval;
|
||||
private long pingTimeout;
|
||||
private String id;
|
||||
private String hostname;
|
||||
private String path;
|
||||
private String timestampParam;
|
||||
private List<String> transports;
|
||||
private List<String> upgrades;
|
||||
private Map<String, String> query;
|
||||
/*package*/ LinkedList<Packet> writeBuffer = new LinkedList<Packet>();
|
||||
private LinkedList<Runnable> callbackBuffer = new LinkedList<Runnable>();
|
||||
/*package*/ Transport transport;
|
||||
private Future pingTimeoutTimer;
|
||||
private Future pingIntervalTimer;
|
||||
private SSLContext sslContext;
|
||||
private HostnameVerifier hostnameVerifier;
|
||||
|
||||
private ReadyState readyState;
|
||||
private ScheduledExecutorService heartbeatScheduler;
|
||||
|
||||
public static void setDefaultSSLContext(SSLContext sslContext) {
|
||||
defaultSSLContext = sslContext;
|
||||
}
|
||||
|
||||
public static void setDefaultHostnameVerifier(HostnameVerifier hostnameVerifier) {
|
||||
defaultHostnameVerifier = hostnameVerifier;
|
||||
}
|
||||
|
||||
public Socket() {
|
||||
this(new Options());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket.
|
||||
*
|
||||
* @param uri URI to connect.
|
||||
* @throws URISyntaxException
|
||||
*/
|
||||
public Socket(String uri) throws URISyntaxException {
|
||||
this(uri, null);
|
||||
}
|
||||
|
||||
public Socket(URI uri) {
|
||||
this(uri, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a socket with options.
|
||||
*
|
||||
* @param uri URI to connect.
|
||||
* @param opts options for socket
|
||||
* @throws URISyntaxException
|
||||
*/
|
||||
public Socket(String uri, Options opts) throws URISyntaxException {
|
||||
this(uri == null ? null : new URI(uri), opts);
|
||||
}
|
||||
|
||||
public Socket(URI uri, Options opts) {
|
||||
this(uri == null ? opts : Options.fromURI(uri, opts));
|
||||
}
|
||||
|
||||
public Socket(Options opts) {
|
||||
if (opts.host != null) {
|
||||
boolean ipv6uri = opts.host.indexOf(']') != -1;
|
||||
String[] pieces = ipv6uri ? opts.host.split("]:") : opts.host.split(":");
|
||||
boolean ipv6 = (pieces.length > 2 || opts.host.indexOf("::") == -1);
|
||||
if (ipv6) {
|
||||
opts.hostname = opts.host;
|
||||
} else {
|
||||
opts.hostname = pieces[0];
|
||||
if (ipv6uri) {
|
||||
opts.hostname = opts.hostname.substring(1);
|
||||
}
|
||||
if (pieces.length > 1) {
|
||||
opts.port = Integer.parseInt(pieces[pieces.length - 1]);
|
||||
} else if (opts.port == -1) {
|
||||
// if no port is specified manually, use the protocol default
|
||||
opts.port = this.secure ? 443 : 80;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.secure = opts.secure;
|
||||
this.sslContext = opts.sslContext != null ? opts.sslContext : defaultSSLContext;
|
||||
this.hostname = opts.hostname != null ? opts.hostname : "localhost";
|
||||
this.port = opts.port != 0 ? opts.port : (this.secure ? 443 : 80);
|
||||
this.query = opts.query != null ?
|
||||
ParseQS.decode(opts.query) : new HashMap<String, String>();
|
||||
this.upgrade = opts.upgrade;
|
||||
this.path = (opts.path != null ? opts.path : "/engine.io").replaceAll("/$", "") + "/";
|
||||
this.timestampParam = opts.timestampParam != null ? opts.timestampParam : "t";
|
||||
this.timestampRequests = opts.timestampRequests;
|
||||
this.transports = new ArrayList<String>(Arrays.asList(opts.transports != null ?
|
||||
opts.transports : new String[]{Polling.NAME, WebSocket.NAME}));
|
||||
this.policyPort = opts.policyPort != 0 ? opts.policyPort : 843;
|
||||
this.rememberUpgrade = opts.rememberUpgrade;
|
||||
this.hostnameVerifier = opts.hostnameVerifier != null ? opts.hostnameVerifier : defaultHostnameVerifier;
|
||||
}
|
||||
|
||||
/**
|
||||
* Connects the client.
|
||||
*
|
||||
* @return a reference to to this object.
|
||||
*/
|
||||
public Socket open() {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
String transportName;
|
||||
if (Socket.this.rememberUpgrade && Socket.priorWebsocketSuccess && Socket.this.transports.contains(WebSocket.NAME)) {
|
||||
transportName = WebSocket.NAME;
|
||||
} else if (0 == Socket.this.transports.size()) {
|
||||
// Emit error on next tick so it can be listened to
|
||||
final Socket self = Socket.this;
|
||||
EventThread.nextTick(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.emit(Socket.EVENT_ERROR, new EngineIOException("No transports available"));
|
||||
}
|
||||
});
|
||||
return;
|
||||
} else {
|
||||
transportName = Socket.this.transports.get(0);
|
||||
}
|
||||
Socket.this.readyState = ReadyState.OPENING;
|
||||
Transport transport = Socket.this.createTransport(transportName);
|
||||
Socket.this.setTransport(transport);
|
||||
transport.open();
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
private Transport createTransport(String name) {
|
||||
logger.fine(String.format("creating transport '%s'", name));
|
||||
Map<String, String> query = new HashMap<String, String>(this.query);
|
||||
|
||||
query.put("EIO", String.valueOf(Parser.protocol));
|
||||
query.put("transport", name);
|
||||
if (this.id != null) {
|
||||
query.put("sid", this.id);
|
||||
}
|
||||
|
||||
Transport.Options opts = new Transport.Options();
|
||||
opts.sslContext = this.sslContext;
|
||||
opts.hostname = this.hostname;
|
||||
opts.port = this.port;
|
||||
opts.secure = this.secure;
|
||||
opts.path = this.path;
|
||||
opts.query = query;
|
||||
opts.timestampRequests = this.timestampRequests;
|
||||
opts.timestampParam = this.timestampParam;
|
||||
opts.policyPort = this.policyPort;
|
||||
opts.socket = this;
|
||||
opts.hostnameVerifier = this.hostnameVerifier;
|
||||
|
||||
Transport transport;
|
||||
if (WebSocket.NAME.equals(name)) {
|
||||
transport = new WebSocket(opts);
|
||||
} else if (Polling.NAME.equals(name)) {
|
||||
transport = new PollingXHR(opts);
|
||||
} else {
|
||||
throw new RuntimeException();
|
||||
}
|
||||
|
||||
this.emit(EVENT_TRANSPORT, transport);
|
||||
|
||||
return transport;
|
||||
}
|
||||
|
||||
private void setTransport(Transport transport) {
|
||||
logger.fine(String.format("setting transport %s", transport.name));
|
||||
final Socket self = this;
|
||||
|
||||
if (this.transport != null) {
|
||||
logger.fine(String.format("clearing existing transport %s", this.transport.name));
|
||||
this.transport.off();
|
||||
}
|
||||
|
||||
this.transport = transport;
|
||||
|
||||
transport.on(Transport.EVENT_DRAIN, new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
self.onDrain();
|
||||
}
|
||||
}).on(Transport.EVENT_PACKET, new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
self.onPacket(args.length > 0 ? (Packet) args[0] : null);
|
||||
}
|
||||
}).on(Transport.EVENT_ERROR, new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
self.onError(args.length > 0 ? (Exception) args[0] : null);
|
||||
}
|
||||
}).on(Transport.EVENT_CLOSE, new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
self.onClose("transport close");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void probe(final String name) {
|
||||
logger.fine(String.format("probing transport '%s'", name));
|
||||
final Transport[] transport = new Transport[] {this.createTransport(name)};
|
||||
final boolean[] failed = new boolean[] {false};
|
||||
final Socket self = this;
|
||||
|
||||
Socket.priorWebsocketSuccess = false;
|
||||
|
||||
final Runnable[] cleanup = new Runnable[1];
|
||||
|
||||
final Listener onTransportOpen = new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
if (failed[0]) return;
|
||||
|
||||
logger.fine(String.format("probe transport '%s' opened", name));
|
||||
Packet<String> packet = new Packet<String>(Packet.PING, "probe");
|
||||
transport[0].send(new Packet[] {packet});
|
||||
transport[0].once(Transport.EVENT_PACKET, new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
if (failed[0]) return;
|
||||
|
||||
Packet msg = (Packet)args[0];
|
||||
if (Packet.PONG.equals(msg.type) && "probe".equals(msg.data)) {
|
||||
logger.fine(String.format("probe transport '%s' pong", name));
|
||||
self.upgrading = true;
|
||||
self.emit(EVENT_UPGRADING, transport[0]);
|
||||
if (null == transport[0]) return;
|
||||
Socket.priorWebsocketSuccess = WebSocket.NAME.equals(transport[0].name);
|
||||
|
||||
logger.fine(String.format("pausing current transport '%s'", self.transport.name));
|
||||
((Polling)self.transport).pause(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (failed[0]) return;
|
||||
if (ReadyState.CLOSED == self.readyState) return;
|
||||
|
||||
logger.fine("changing transport and sending upgrade packet");
|
||||
|
||||
cleanup[0].run();
|
||||
|
||||
self.setTransport(transport[0]);
|
||||
Packet packet = new Packet(Packet.UPGRADE);
|
||||
transport[0].send(new Packet[]{packet});
|
||||
self.emit(EVENT_UPGRADE, transport[0]);
|
||||
transport[0] = null;
|
||||
self.upgrading = false;
|
||||
self.flush();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
logger.fine(String.format("probe transport '%s' failed", name));
|
||||
EngineIOException err = new EngineIOException("probe error");
|
||||
err.transport = transport[0].name;
|
||||
self.emit(EVENT_UPGRADE_ERROR, err);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
final Listener freezeTransport = new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
if (failed[0]) return;
|
||||
|
||||
failed[0] = true;
|
||||
|
||||
cleanup[0].run();
|
||||
|
||||
transport[0].close();
|
||||
transport[0] = null;
|
||||
}
|
||||
};
|
||||
|
||||
// Handle any error that happens while probing
|
||||
final Listener onerror = new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
Object err = args[0];
|
||||
EngineIOException error;
|
||||
if (err instanceof Exception) {
|
||||
error = new EngineIOException("probe error", (Exception)err);
|
||||
} else if (err instanceof String) {
|
||||
error = new EngineIOException("probe error: " + (String)err);
|
||||
} else {
|
||||
error = new EngineIOException("probe error");
|
||||
}
|
||||
error.transport = transport[0].name;
|
||||
|
||||
freezeTransport.call();
|
||||
|
||||
logger.fine(String.format("probe transport \"%s\" failed because of error: %s", name, err));
|
||||
|
||||
self.emit(EVENT_UPGRADE_ERROR, error);
|
||||
}
|
||||
};
|
||||
|
||||
final Listener onTransportClose = new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
onerror.call("transport closed");
|
||||
}
|
||||
};
|
||||
|
||||
// When the socket is closed while we're probing
|
||||
final Listener onclose = new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
onerror.call("socket closed");
|
||||
}
|
||||
};
|
||||
|
||||
// When the socket is upgraded while we're probing
|
||||
final Listener onupgrade = new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
Transport to = (Transport)args[0];
|
||||
if (transport[0] != null && !to.name.equals(transport[0].name)) {
|
||||
logger.fine(String.format("'%s' works - aborting '%s'", to.name, transport[0].name));
|
||||
freezeTransport.call();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
cleanup[0] = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
transport[0].off(Transport.EVENT_OPEN, onTransportOpen);
|
||||
transport[0].off(Transport.EVENT_ERROR, onerror);
|
||||
transport[0].off(Transport.EVENT_CLOSE, onTransportClose);
|
||||
self.off(EVENT_CLOSE, onclose);
|
||||
self.off(EVENT_UPGRADING, onupgrade);
|
||||
}
|
||||
};
|
||||
|
||||
transport[0].once(Transport.EVENT_OPEN, onTransportOpen);
|
||||
transport[0].once(Transport.EVENT_ERROR, onerror);
|
||||
transport[0].once(Transport.EVENT_CLOSE, onTransportClose);
|
||||
|
||||
this.once(EVENT_CLOSE, onclose);
|
||||
this.once(EVENT_UPGRADING, onupgrade);
|
||||
|
||||
transport[0].open();
|
||||
}
|
||||
|
||||
private void onOpen() {
|
||||
logger.fine("socket open");
|
||||
this.readyState = ReadyState.OPEN;
|
||||
Socket.priorWebsocketSuccess = WebSocket.NAME.equals(this.transport.name);
|
||||
this.emit(EVENT_OPEN);
|
||||
this.flush();
|
||||
|
||||
if (this.readyState == ReadyState.OPEN && this.upgrade && this.transport instanceof Polling) {
|
||||
logger.fine("starting upgrade probes");
|
||||
for (String upgrade: this.upgrades) {
|
||||
this.probe(upgrade);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void onPacket(Packet packet) {
|
||||
if (this.readyState == ReadyState.OPENING || this.readyState == ReadyState.OPEN) {
|
||||
logger.fine(String.format("socket received: type '%s', data '%s'", packet.type, packet.data));
|
||||
|
||||
this.emit(EVENT_PACKET, packet);
|
||||
this.emit(EVENT_HEARTBEAT);
|
||||
|
||||
if (Packet.OPEN.equals(packet.type)) {
|
||||
try {
|
||||
this.onHandshake(new HandshakeData((String)packet.data));
|
||||
} catch (JSONException e) {
|
||||
this.emit(EVENT_ERROR, new EngineIOException(e));
|
||||
}
|
||||
} else if (Packet.PONG.equals(packet.type)) {
|
||||
this.setPing();
|
||||
} else if (Packet.ERROR.equals(packet.type)) {
|
||||
EngineIOException err = new EngineIOException("server error");
|
||||
err.code = packet.data;
|
||||
this.emit(EVENT_ERROR, err);
|
||||
} else if (Packet.MESSAGE.equals(packet.type)) {
|
||||
this.emit(EVENT_DATA, packet.data);
|
||||
this.emit(EVENT_MESSAGE, packet.data);
|
||||
}
|
||||
} else {
|
||||
logger.fine(String.format("packet received with socket readyState '%s'", this.readyState));
|
||||
}
|
||||
}
|
||||
|
||||
private void onHandshake(HandshakeData data) {
|
||||
this.emit(EVENT_HANDSHAKE, data);
|
||||
this.id = data.sid;
|
||||
this.transport.query.put("sid", data.sid);
|
||||
this.upgrades = this.filterUpgrades(Arrays.asList(data.upgrades));
|
||||
this.pingInterval = data.pingInterval;
|
||||
this.pingTimeout = data.pingTimeout;
|
||||
this.onOpen();
|
||||
// In case open handler closes socket
|
||||
if (ReadyState.CLOSED == this.readyState) return;
|
||||
this.setPing();
|
||||
|
||||
this.off(EVENT_HEARTBEAT, this.onHeartbeatAsListener);
|
||||
this.on(EVENT_HEARTBEAT, this.onHeartbeatAsListener);
|
||||
}
|
||||
|
||||
private final Listener onHeartbeatAsListener = new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
Socket.this.onHeartbeat(args.length > 0 ? (Long)args[0]: 0);
|
||||
}
|
||||
};
|
||||
|
||||
private void onHeartbeat(long timeout) {
|
||||
if (this.pingTimeoutTimer != null) {
|
||||
pingTimeoutTimer.cancel(false);
|
||||
}
|
||||
|
||||
if (timeout <= 0) {
|
||||
timeout = this.pingInterval + this.pingTimeout;
|
||||
}
|
||||
|
||||
final Socket self = this;
|
||||
this.pingTimeoutTimer = this.getHeartbeatScheduler().schedule(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (self.readyState == ReadyState.CLOSED) return;
|
||||
self.onClose("ping timeout");
|
||||
}
|
||||
});
|
||||
}
|
||||
}, timeout, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
private void setPing() {
|
||||
if (this.pingIntervalTimer != null) {
|
||||
pingIntervalTimer.cancel(false);
|
||||
}
|
||||
|
||||
final Socket self = this;
|
||||
this.pingIntervalTimer = this.getHeartbeatScheduler().schedule(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
logger.fine(String.format("writing ping packet - expecting pong within %sms", self.pingTimeout));
|
||||
self.ping();
|
||||
self.onHeartbeat(self.pingTimeout);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, this.pingInterval, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a ping packet.
|
||||
*/
|
||||
public void ping() {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Socket.this.sendPacket(Packet.PING);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void onDrain() {
|
||||
for (int i = 0; i < this.prevBufferLen; i++) {
|
||||
Runnable callback = this.callbackBuffer.get(i);
|
||||
if (callback != null) {
|
||||
callback.run();
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < this.prevBufferLen; i++) {
|
||||
this.writeBuffer.poll();
|
||||
this.callbackBuffer.poll();
|
||||
}
|
||||
|
||||
this.prevBufferLen = 0;
|
||||
if (this.writeBuffer.size() == 0) {
|
||||
this.emit(EVENT_DRAIN);
|
||||
} else {
|
||||
this.flush();
|
||||
}
|
||||
}
|
||||
|
||||
private void flush() {
|
||||
if (this.readyState != ReadyState.CLOSED && this.transport.writable &&
|
||||
!this.upgrading && this.writeBuffer.size() != 0) {
|
||||
logger.fine(String.format("flushing %d packets in socket", this.writeBuffer.size()));
|
||||
this.prevBufferLen = this.writeBuffer.size();
|
||||
this.transport.send(this.writeBuffer.toArray(new Packet[this.writeBuffer.size()]));
|
||||
this.emit(EVENT_FLUSH);
|
||||
}
|
||||
}
|
||||
|
||||
public void write(String msg) {
|
||||
this.write(msg, null);
|
||||
}
|
||||
|
||||
public void write(String msg, Runnable fn) {
|
||||
this.send(msg, fn);
|
||||
}
|
||||
|
||||
public void write(byte[] msg) {
|
||||
this.write(msg, null);
|
||||
}
|
||||
|
||||
public void write(byte[] msg, Runnable fn) {
|
||||
this.send(msg, fn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message.
|
||||
*
|
||||
* @param msg
|
||||
*/
|
||||
public void send(String msg) {
|
||||
this.send(msg, null);
|
||||
}
|
||||
|
||||
public void send(byte[] msg) {
|
||||
this.send(msg, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a message.
|
||||
*
|
||||
* @param msg
|
||||
* @param fn callback to be called on drain
|
||||
*/
|
||||
public void send(final String msg, final Runnable fn) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Socket.this.sendPacket(Packet.MESSAGE, msg, fn);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public void send(final byte[] msg, final Runnable fn) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Socket.this.sendPacket(Packet.MESSAGE, msg, fn);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void sendPacket(String type) {
|
||||
this.sendPacket(new Packet(type), null);
|
||||
}
|
||||
|
||||
private void sendPacket(String type, String data, Runnable fn) {
|
||||
Packet<String> packet = new Packet<String>(type, data);
|
||||
sendPacket(packet, fn);
|
||||
}
|
||||
|
||||
private void sendPacket(String type, byte[] data, Runnable fn) {
|
||||
Packet<byte[]> packet = new Packet<byte[]>(type, data);
|
||||
sendPacket(packet, fn);
|
||||
}
|
||||
|
||||
private void sendPacket(Packet packet, Runnable fn) {
|
||||
if (ReadyState.CLOSING == this.readyState || ReadyState.CLOSED == this.readyState) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (fn == null) {
|
||||
// ConcurrentLinkedList does not permit `null`.
|
||||
fn = noop;
|
||||
}
|
||||
|
||||
this.emit(EVENT_PACKET_CREATE, packet);
|
||||
this.writeBuffer.offer(packet);
|
||||
this.callbackBuffer.offer(fn);
|
||||
this.flush();
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnects the client.
|
||||
*
|
||||
* @return a reference to to this object.
|
||||
*/
|
||||
public Socket close() {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (Socket.this.readyState == ReadyState.OPENING || Socket.this.readyState == ReadyState.OPEN) {
|
||||
Socket.this.readyState = ReadyState.CLOSING;
|
||||
|
||||
final Socket self = Socket.this;
|
||||
|
||||
final Runnable close = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.onClose("forced close");
|
||||
logger.fine("socket closing - telling transport to close");
|
||||
self.transport.close();
|
||||
}
|
||||
};
|
||||
|
||||
final Listener[] cleanupAndClose = new Listener[1];
|
||||
cleanupAndClose[0] = new Listener() {
|
||||
@Override
|
||||
public void call(Object ...args) {
|
||||
self.off(EVENT_UPGRADE, cleanupAndClose[0]);
|
||||
self.off(EVENT_UPGRADE_ERROR, cleanupAndClose[0]);
|
||||
close.run();
|
||||
}
|
||||
};
|
||||
|
||||
final Runnable waitForUpgrade = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
// wait for updade to finish since we can't send packets while pausing a transport
|
||||
self.once(EVENT_UPGRADE, cleanupAndClose[0]);
|
||||
self.once(EVENT_UPGRADE_ERROR, cleanupAndClose[0]);
|
||||
}
|
||||
};
|
||||
|
||||
if (Socket.this.writeBuffer.size() > 0) {
|
||||
Socket.this.once(EVENT_DRAIN, new Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
if (Socket.this.upgrading) {
|
||||
waitForUpgrade.run();
|
||||
} else {
|
||||
close.run();
|
||||
}
|
||||
}
|
||||
});
|
||||
} else if (Socket.this.upgrading) {
|
||||
waitForUpgrade.run();
|
||||
} else {
|
||||
close.run();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
private void onError(Exception err) {
|
||||
logger.fine(String.format("socket error %s", err));
|
||||
Socket.priorWebsocketSuccess = false;
|
||||
this.emit(EVENT_ERROR, err);
|
||||
this.onClose("transport error", err);
|
||||
}
|
||||
|
||||
private void onClose(String reason) {
|
||||
this.onClose(reason, null);
|
||||
}
|
||||
|
||||
private void onClose(String reason, Exception desc) {
|
||||
if (ReadyState.OPENING == this.readyState || ReadyState.OPEN == this.readyState || ReadyState.CLOSING == this.readyState) {
|
||||
logger.fine(String.format("socket close with reason: %s", reason));
|
||||
final Socket self = this;
|
||||
|
||||
// clear timers
|
||||
if (this.pingIntervalTimer != null) {
|
||||
this.pingIntervalTimer.cancel(false);
|
||||
}
|
||||
if (this.pingTimeoutTimer != null) {
|
||||
this.pingTimeoutTimer.cancel(false);
|
||||
}
|
||||
if (this.heartbeatScheduler != null) {
|
||||
this.heartbeatScheduler.shutdown();
|
||||
}
|
||||
|
||||
EventThread.nextTick(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.writeBuffer.clear();
|
||||
self.callbackBuffer.clear();
|
||||
self.prevBufferLen = 0;
|
||||
}
|
||||
});
|
||||
|
||||
// stop event from firing again for transport
|
||||
this.transport.off(EVENT_CLOSE);
|
||||
|
||||
// ensure transport won't stay open
|
||||
this.transport.close();
|
||||
|
||||
// ignore further transport communication
|
||||
this.transport.off();
|
||||
|
||||
// set ready state
|
||||
this.readyState = ReadyState.CLOSED;
|
||||
|
||||
// clear session id
|
||||
this.id = null;
|
||||
|
||||
// emit close events
|
||||
this.emit(EVENT_CLOSE, reason, desc);
|
||||
}
|
||||
}
|
||||
|
||||
/*package*/ List<String > filterUpgrades(List<String> upgrades) {
|
||||
List<String> filteredUpgrades = new ArrayList<String>();
|
||||
for (String upgrade : upgrades) {
|
||||
if (this.transports.contains(upgrade)) {
|
||||
filteredUpgrades.add(upgrade);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return filteredUpgrades;
|
||||
}
|
||||
|
||||
public String id() {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
private ScheduledExecutorService getHeartbeatScheduler() {
|
||||
if (this.heartbeatScheduler == null || this.heartbeatScheduler.isShutdown()) {
|
||||
this.heartbeatScheduler = Executors.newSingleThreadScheduledExecutor();
|
||||
}
|
||||
return this.heartbeatScheduler;
|
||||
}
|
||||
|
||||
public static class Options extends Transport.Options {
|
||||
|
||||
/**
|
||||
* List of transport names.
|
||||
*/
|
||||
public String[] transports;
|
||||
|
||||
/**
|
||||
* Whether to upgrade the transport. Defaults to `true`.
|
||||
*/
|
||||
public boolean upgrade = true;
|
||||
|
||||
public boolean rememberUpgrade;
|
||||
public String host;
|
||||
public String query;
|
||||
|
||||
|
||||
private static Options fromURI(URI uri, Options opts) {
|
||||
if (opts == null) {
|
||||
opts = new Options();
|
||||
}
|
||||
|
||||
opts.host = uri.getHost();
|
||||
opts.secure = "https".equals(uri.getScheme()) || "wss".equals(uri.getScheme());
|
||||
opts.port = uri.getPort();
|
||||
|
||||
String query = uri.getRawQuery();
|
||||
if (query != null) {
|
||||
opts.query = query;
|
||||
}
|
||||
|
||||
return opts;
|
||||
}
|
||||
}
|
||||
}
|
||||
153
src/main/java/io/socket/engineio/client/Transport.java
Normal file
153
src/main/java/io/socket/engineio/client/Transport.java
Normal file
@@ -0,0 +1,153 @@
|
||||
package io.socket.engineio.client;
|
||||
|
||||
|
||||
import io.socket.emitter.Emitter;
|
||||
import io.socket.engineio.parser.Packet;
|
||||
import io.socket.engineio.parser.Parser;
|
||||
import io.socket.thread.EventThread;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.util.Map;
|
||||
|
||||
public abstract class Transport extends Emitter {
|
||||
|
||||
protected enum ReadyState {
|
||||
OPENING, OPEN, CLOSED, PAUSED;
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return super.toString().toLowerCase();
|
||||
}
|
||||
}
|
||||
|
||||
public static final String EVENT_OPEN = "open";
|
||||
public static final String EVENT_CLOSE = "close";
|
||||
public static final String EVENT_PACKET = "packet";
|
||||
public static final String EVENT_DRAIN = "drain";
|
||||
public static final String EVENT_ERROR = "error";
|
||||
public static final String EVENT_REQUEST_HEADERS = "requestHeaders";
|
||||
public static final String EVENT_RESPONSE_HEADERS = "responseHeaders";
|
||||
|
||||
protected static int timestamps = 0;
|
||||
|
||||
public boolean writable;
|
||||
public String name;
|
||||
public Map<String, String> query;
|
||||
|
||||
protected boolean secure;
|
||||
protected boolean timestampRequests;
|
||||
protected int port;
|
||||
protected String path;
|
||||
protected String hostname;
|
||||
protected String timestampParam;
|
||||
protected SSLContext sslContext;
|
||||
protected Socket socket;
|
||||
protected HostnameVerifier hostnameVerifier;
|
||||
|
||||
protected ReadyState readyState;
|
||||
|
||||
public Transport(Options opts) {
|
||||
this.path = opts.path;
|
||||
this.hostname = opts.hostname;
|
||||
this.port = opts.port;
|
||||
this.secure = opts.secure;
|
||||
this.query = opts.query;
|
||||
this.timestampParam = opts.timestampParam;
|
||||
this.timestampRequests = opts.timestampRequests;
|
||||
this.sslContext = opts.sslContext;
|
||||
this.socket = opts.socket;
|
||||
this.hostnameVerifier = opts.hostnameVerifier;
|
||||
}
|
||||
|
||||
protected Transport onError(String msg, Exception desc) {
|
||||
// TODO: handle error
|
||||
Exception err = new EngineIOException(msg, desc);
|
||||
this.emit(EVENT_ERROR, err);
|
||||
return this;
|
||||
}
|
||||
|
||||
public Transport open() {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (Transport.this.readyState == ReadyState.CLOSED || Transport.this.readyState == null) {
|
||||
Transport.this.readyState = ReadyState.OPENING;
|
||||
Transport.this.doOpen();
|
||||
}
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
public Transport close() {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (Transport.this.readyState == ReadyState.OPENING || Transport.this.readyState == ReadyState.OPEN) {
|
||||
Transport.this.doClose();
|
||||
Transport.this.onClose();
|
||||
}
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
public void send(final Packet[] packets) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (Transport.this.readyState == ReadyState.OPEN) {
|
||||
Transport.this.write(packets);
|
||||
} else {
|
||||
throw new RuntimeException("Transport not open");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected void onOpen() {
|
||||
this.readyState = ReadyState.OPEN;
|
||||
this.writable = true;
|
||||
this.emit(EVENT_OPEN);
|
||||
}
|
||||
|
||||
protected void onData(String data) {
|
||||
this.onPacket(Parser.decodePacket(data));
|
||||
}
|
||||
|
||||
protected void onData(byte[] data) {
|
||||
this.onPacket(Parser.decodePacket(data));
|
||||
}
|
||||
|
||||
protected void onPacket(Packet packet) {
|
||||
this.emit(EVENT_PACKET, packet);
|
||||
}
|
||||
|
||||
protected void onClose() {
|
||||
this.readyState = ReadyState.CLOSED;
|
||||
this.emit(EVENT_CLOSE);
|
||||
}
|
||||
|
||||
abstract protected void write(Packet[] packets);
|
||||
|
||||
abstract protected void doOpen();
|
||||
|
||||
abstract protected void doClose();
|
||||
|
||||
|
||||
public static class Options {
|
||||
|
||||
public String hostname;
|
||||
public String path;
|
||||
public String timestampParam;
|
||||
public boolean secure;
|
||||
public boolean timestampRequests;
|
||||
public int port = -1;
|
||||
public int policyPort = -1;
|
||||
public Map<String, String> query;
|
||||
public SSLContext sslContext;
|
||||
public HostnameVerifier hostnameVerifier;
|
||||
protected Socket socket;
|
||||
}
|
||||
}
|
||||
218
src/main/java/io/socket/engineio/client/transports/Polling.java
Normal file
218
src/main/java/io/socket/engineio/client/transports/Polling.java
Normal file
@@ -0,0 +1,218 @@
|
||||
package io.socket.engineio.client.transports;
|
||||
|
||||
|
||||
import io.socket.engineio.client.Transport;
|
||||
import io.socket.engineio.parser.Packet;
|
||||
import io.socket.engineio.parser.Parser;
|
||||
import io.socket.parseqs.ParseQS;
|
||||
import io.socket.thread.EventThread;
|
||||
import io.socket.emitter.Emitter;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
abstract public class Polling extends Transport {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(Polling.class.getName());
|
||||
|
||||
public static final String NAME = "polling";
|
||||
|
||||
public static final String EVENT_POLL = "poll";
|
||||
public static final String EVENT_POLL_COMPLETE = "pollComplete";
|
||||
|
||||
private boolean polling;
|
||||
|
||||
|
||||
public Polling(Options opts) {
|
||||
super(opts);
|
||||
this.name = NAME;
|
||||
}
|
||||
|
||||
protected void doOpen() {
|
||||
this.poll();
|
||||
}
|
||||
|
||||
public void pause(final Runnable onPause) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
final Polling self = Polling.this;
|
||||
|
||||
Polling.this.readyState = ReadyState.PAUSED;
|
||||
|
||||
final Runnable pause = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
logger.fine("paused");
|
||||
self.readyState = ReadyState.PAUSED;
|
||||
onPause.run();
|
||||
}
|
||||
};
|
||||
|
||||
if (Polling.this.polling || !Polling.this.writable) {
|
||||
final int[] total = new int[]{0};
|
||||
|
||||
if (Polling.this.polling) {
|
||||
logger.fine("we are currently polling - waiting to pause");
|
||||
total[0]++;
|
||||
Polling.this.once(EVENT_POLL_COMPLETE, new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
logger.fine("pre-pause polling complete");
|
||||
if (--total[0] == 0) {
|
||||
pause.run();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (!Polling.this.writable) {
|
||||
logger.fine("we are currently writing - waiting to pause");
|
||||
total[0]++;
|
||||
Polling.this.once(EVENT_DRAIN, new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
logger.fine("pre-pause writing complete");
|
||||
if (--total[0] == 0) {
|
||||
pause.run();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
pause.run();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void poll() {
|
||||
logger.fine("polling");
|
||||
this.polling = true;
|
||||
this.doPoll();
|
||||
this.emit(EVENT_POLL);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onData(String data) {
|
||||
_onData(data);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onData(byte[] data) {
|
||||
_onData(data);
|
||||
}
|
||||
|
||||
private void _onData(Object data) {
|
||||
final Polling self = this;
|
||||
logger.fine(String.format("polling got data %s", data));
|
||||
Parser.DecodePayloadCallback callback = new Parser.DecodePayloadCallback() {
|
||||
@Override
|
||||
public boolean call(Packet packet, int index, int total) {
|
||||
if (self.readyState == ReadyState.OPENING) {
|
||||
self.onOpen();
|
||||
}
|
||||
|
||||
if (Packet.CLOSE.equals(packet.type)) {
|
||||
self.onClose();
|
||||
return false;
|
||||
}
|
||||
|
||||
self.onPacket(packet);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
if (data instanceof String) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Parser.DecodePayloadCallback<String> _callback = callback;
|
||||
Parser.decodePayload((String)data, _callback);
|
||||
} else if (data instanceof byte[]) {
|
||||
Parser.decodePayload((byte[])data, callback);
|
||||
}
|
||||
|
||||
if (this.readyState != ReadyState.CLOSED) {
|
||||
this.polling = false;
|
||||
this.emit(EVENT_POLL_COMPLETE);
|
||||
|
||||
if (this.readyState == ReadyState.OPEN) {
|
||||
this.poll();
|
||||
} else {
|
||||
logger.fine(String.format("ignoring poll - transport state '%s'", this.readyState));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected void doClose() {
|
||||
final Polling self = this;
|
||||
|
||||
Emitter.Listener close = new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
logger.fine("writing close packet");
|
||||
self.write(new Packet[] {new Packet(Packet.CLOSE)});
|
||||
}
|
||||
};
|
||||
|
||||
if (this.readyState == ReadyState.OPEN) {
|
||||
logger.fine("transport open - closing");
|
||||
close.call();
|
||||
} else {
|
||||
// in case we're trying to close while
|
||||
// handshaking is in progress (engine.io-client GH-164)
|
||||
logger.fine("transport not open - deferring close");
|
||||
this.once(EVENT_OPEN, close);
|
||||
}
|
||||
}
|
||||
|
||||
protected void write(Packet[] packets) {
|
||||
final Polling self = this;
|
||||
this.writable = false;
|
||||
final Runnable callbackfn = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.writable = true;
|
||||
self.emit(EVENT_DRAIN);
|
||||
}
|
||||
};
|
||||
|
||||
Parser.encodePayload(packets, new Parser.EncodeCallback<byte[]>() {
|
||||
@Override
|
||||
public void call(byte[] data) {
|
||||
self.doWrite(data, callbackfn);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected String uri() {
|
||||
Map<String, String> query = this.query;
|
||||
if (query == null) {
|
||||
query = new HashMap<String, String>();
|
||||
}
|
||||
String schema = this.secure ? "https" : "http";
|
||||
String port = "";
|
||||
|
||||
if (this.timestampRequests) {
|
||||
query.put(this.timestampParam, String.valueOf(new Date().getTime()) + "-" + Transport.timestamps++);
|
||||
}
|
||||
|
||||
String _query = ParseQS.encode(query);
|
||||
|
||||
if (this.port > 0 && (("https".equals(schema) && this.port != 443)
|
||||
|| ("http".equals(schema) && this.port != 80))) {
|
||||
port = ":" + this.port;
|
||||
}
|
||||
|
||||
if (_query.length() > 0) {
|
||||
_query = "?" + _query;
|
||||
}
|
||||
|
||||
return schema + "://" + this.hostname + port + this.path + _query;
|
||||
}
|
||||
|
||||
abstract protected void doWrite(byte[] data, Runnable fn);
|
||||
|
||||
abstract protected void doPoll();
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
package io.socket.engineio.client.transports;
|
||||
|
||||
|
||||
import io.socket.emitter.Emitter;
|
||||
import io.socket.thread.EventThread;
|
||||
import io.socket.engineio.client.Transport;
|
||||
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.HttpsURLConnection;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.*;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
public class PollingXHR extends Polling {
|
||||
|
||||
private static final Logger logger = Logger.getLogger(PollingXHR.class.getName());
|
||||
|
||||
private Request sendXhr;
|
||||
private Request pollXhr;
|
||||
|
||||
public PollingXHR(Transport.Options opts) {
|
||||
super(opts);
|
||||
}
|
||||
|
||||
protected Request request() {
|
||||
return this.request(null);
|
||||
}
|
||||
|
||||
protected Request request(Request.Options opts) {
|
||||
if (opts == null) {
|
||||
opts = new Request.Options();
|
||||
}
|
||||
opts.uri = this.uri();
|
||||
opts.sslContext = this.sslContext;
|
||||
opts.hostnameVerifier = this.hostnameVerifier;
|
||||
|
||||
Request req = new Request(opts);
|
||||
|
||||
final PollingXHR self = this;
|
||||
req.on(Request.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
// Never execute asynchronously for support to modify headers.
|
||||
self.emit(Transport.EVENT_REQUEST_HEADERS, args[0]);
|
||||
}
|
||||
}).on(Request.EVENT_RESPONSE_HEADERS, new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(final Object... args) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.emit(Transport.EVENT_RESPONSE_HEADERS, args[0]);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
return req;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doWrite(byte[] data, final Runnable fn) {
|
||||
Request.Options opts = new Request.Options();
|
||||
opts.method = "POST";
|
||||
opts.data = data;
|
||||
Request req = this.request(opts);
|
||||
final PollingXHR self = this;
|
||||
req.on(Request.EVENT_SUCCESS, new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(Object... args) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
fn.run();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
req.on(Request.EVENT_ERROR, new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(final Object... args) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Exception err = args.length > 0 && args[0] instanceof Exception ? (Exception)args[0] : null;
|
||||
self.onError("xhr post error", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
req.create();
|
||||
this.sendXhr = req;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doPoll() {
|
||||
logger.fine("xhr poll");
|
||||
Request req = this.request();
|
||||
final PollingXHR self = this;
|
||||
req.on(Request.EVENT_DATA, new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(final Object... args) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Object arg = args.length > 0 ? args[0] : null;
|
||||
if (arg instanceof String) {
|
||||
self.onData((String)arg);
|
||||
} else if (arg instanceof byte[]) {
|
||||
self.onData((byte[])arg);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
req.on(Request.EVENT_ERROR, new Emitter.Listener() {
|
||||
@Override
|
||||
public void call(final Object... args) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Exception err = args.length > 0 && args[0] instanceof Exception ? (Exception) args[0] : null;
|
||||
self.onError("xhr poll error", err);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
req.create();
|
||||
this.pollXhr = req;
|
||||
}
|
||||
|
||||
public static class Request extends Emitter {
|
||||
|
||||
public static final String EVENT_SUCCESS = "success";
|
||||
public static final String EVENT_DATA = "data";
|
||||
public static final String EVENT_ERROR = "error";
|
||||
public static final String EVENT_REQUEST_HEADERS = "requestHeaders";
|
||||
public static final String EVENT_RESPONSE_HEADERS = "responseHeaders";
|
||||
|
||||
private String method;
|
||||
private String uri;
|
||||
|
||||
// data is always a binary
|
||||
private byte[] data;
|
||||
|
||||
private SSLContext sslContext;
|
||||
private HttpURLConnection xhr;
|
||||
private HostnameVerifier hostnameVerifier;
|
||||
|
||||
public Request(Options opts) {
|
||||
this.method = opts.method != null ? opts.method : "GET";
|
||||
this.uri = opts.uri;
|
||||
this.data = opts.data;
|
||||
this.sslContext = opts.sslContext;
|
||||
this.hostnameVerifier = opts.hostnameVerifier;
|
||||
}
|
||||
|
||||
public void create() {
|
||||
final Request self = this;
|
||||
try {
|
||||
logger.fine(String.format("xhr open %s: %s", this.method, this.uri));
|
||||
URL url = new URL(this.uri);
|
||||
xhr = (HttpURLConnection)url.openConnection();
|
||||
xhr.setRequestMethod(this.method);
|
||||
} catch (IOException e) {
|
||||
this.onError(e);
|
||||
return;
|
||||
}
|
||||
|
||||
xhr.setConnectTimeout(10000);
|
||||
|
||||
if (xhr instanceof HttpsURLConnection) {
|
||||
if (this.sslContext != null) {
|
||||
((HttpsURLConnection)xhr).setSSLSocketFactory(this.sslContext.getSocketFactory());
|
||||
}
|
||||
if (this.hostnameVerifier != null) {
|
||||
((HttpsURLConnection)xhr).setHostnameVerifier(this.hostnameVerifier);
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
|
||||
|
||||
if ("POST".equals(this.method)) {
|
||||
xhr.setDoOutput(true);
|
||||
headers.put("Content-type", new LinkedList<String>(Arrays.asList("application/octet-stream")));
|
||||
}
|
||||
|
||||
self.onRequestHeaders(headers);
|
||||
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
|
||||
for (String v : header.getValue()){
|
||||
xhr.addRequestProperty(header.getKey(), v);
|
||||
}
|
||||
}
|
||||
|
||||
logger.fine(String.format("sending xhr with url %s | data %s", this.uri, this.data));
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
OutputStream output = null;
|
||||
try {
|
||||
if (self.data != null) {
|
||||
xhr.setFixedLengthStreamingMode(self.data.length);
|
||||
output = new BufferedOutputStream(xhr.getOutputStream());
|
||||
output.write(self.data);
|
||||
output.flush();
|
||||
}
|
||||
|
||||
Map<String, List<String>> headers = xhr.getHeaderFields();
|
||||
self.onResponseHeaders(headers);
|
||||
|
||||
final int statusCode = xhr.getResponseCode();
|
||||
if (HttpURLConnection.HTTP_OK == statusCode) {
|
||||
self.onLoad();
|
||||
} else {
|
||||
self.onError(new IOException(Integer.toString(statusCode)));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
self.onError(e);
|
||||
} finally {
|
||||
try {
|
||||
if (output != null) output.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
private void onSuccess() {
|
||||
this.emit(EVENT_SUCCESS);
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
private void onData(String data) {
|
||||
this.emit(EVENT_DATA, data);
|
||||
this.onSuccess();
|
||||
}
|
||||
|
||||
private void onData(byte[] data) {
|
||||
this.emit(EVENT_DATA, data);
|
||||
this.onSuccess();
|
||||
}
|
||||
|
||||
private void onError(Exception err) {
|
||||
this.emit(EVENT_ERROR, err);
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
private void onRequestHeaders(Map<String, List<String>> headers) {
|
||||
this.emit(EVENT_REQUEST_HEADERS, headers);
|
||||
}
|
||||
|
||||
private void onResponseHeaders(Map<String, List<String>> headers) {
|
||||
this.emit(EVENT_RESPONSE_HEADERS, headers);
|
||||
}
|
||||
|
||||
private void cleanup() {
|
||||
if (xhr == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
xhr.disconnect();
|
||||
xhr = null;
|
||||
}
|
||||
|
||||
private void onLoad() {
|
||||
InputStream input = null;
|
||||
BufferedReader reader = null;
|
||||
String contentType = xhr.getContentType();
|
||||
try {
|
||||
if ("application/octet-stream".equalsIgnoreCase(contentType)) {
|
||||
input = new BufferedInputStream(this.xhr.getInputStream());
|
||||
List<byte[]> buffers = new ArrayList<byte[]>();
|
||||
int capacity = 0;
|
||||
int len = 0;
|
||||
byte[] buffer = new byte[1024];
|
||||
while ((len = input.read(buffer)) > 0) {
|
||||
byte[] _buffer = new byte[len];
|
||||
System.arraycopy(buffer, 0, _buffer, 0, len);
|
||||
buffers.add(_buffer);
|
||||
capacity += len;
|
||||
}
|
||||
ByteBuffer data = ByteBuffer.allocate(capacity);
|
||||
for (byte[] b : buffers) {
|
||||
data.put(b);
|
||||
}
|
||||
this.onData(data.array());
|
||||
} else {
|
||||
String line;
|
||||
StringBuilder data = new StringBuilder();
|
||||
reader = new BufferedReader(new InputStreamReader(xhr.getInputStream()));
|
||||
while ((line = reader.readLine()) != null) {
|
||||
data.append(line);
|
||||
}
|
||||
this.onData(data.toString());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
this.onError(e);
|
||||
} finally {
|
||||
try {
|
||||
if (input != null) input.close();
|
||||
} catch (IOException e) {}
|
||||
try {
|
||||
if (reader != null) reader.close();
|
||||
} catch (IOException e) {}
|
||||
}
|
||||
}
|
||||
public void abort() {
|
||||
this.cleanup();
|
||||
}
|
||||
|
||||
public static class Options {
|
||||
|
||||
public String uri;
|
||||
public String method;
|
||||
public byte[] data;
|
||||
public SSLContext sslContext;
|
||||
public HostnameVerifier hostnameVerifier;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package io.socket.engineio.client.transports;
|
||||
|
||||
|
||||
import io.socket.engineio.client.Transport;
|
||||
import io.socket.engineio.parser.Packet;
|
||||
import io.socket.engineio.parser.Parser;
|
||||
import io.socket.parseqs.ParseQS;
|
||||
import io.socket.thread.EventThread;
|
||||
import com.squareup.okhttp.OkHttpClient;
|
||||
import com.squareup.okhttp.Request;
|
||||
import com.squareup.okhttp.Response;
|
||||
import com.squareup.okhttp.ws.WebSocket.PayloadType;
|
||||
import com.squareup.okhttp.ws.WebSocketCall;
|
||||
import com.squareup.okhttp.ws.WebSocketListener;
|
||||
import okio.Buffer;
|
||||
import okio.BufferedSource;
|
||||
|
||||
import javax.net.ssl.SSLSocketFactory;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import java.util.logging.Logger;
|
||||
|
||||
import static com.squareup.okhttp.ws.WebSocket.PayloadType.BINARY;
|
||||
import static com.squareup.okhttp.ws.WebSocket.PayloadType.TEXT;
|
||||
|
||||
public class WebSocket extends Transport {
|
||||
|
||||
public static final String NAME = "websocket";
|
||||
|
||||
private static final Logger logger = Logger.getLogger(PollingXHR.class.getName());
|
||||
|
||||
private com.squareup.okhttp.ws.WebSocket ws;
|
||||
private WebSocketCall wsCall;
|
||||
|
||||
public WebSocket(Options opts) {
|
||||
super(opts);
|
||||
this.name = NAME;
|
||||
}
|
||||
|
||||
protected void doOpen() {
|
||||
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
|
||||
this.emit(EVENT_REQUEST_HEADERS, headers);
|
||||
|
||||
final WebSocket self = this;
|
||||
final OkHttpClient client = new OkHttpClient();
|
||||
if (this.sslContext != null) {
|
||||
SSLSocketFactory factory = sslContext.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault();
|
||||
client.setSslSocketFactory(factory);
|
||||
}
|
||||
if (this.hostnameVerifier != null) {
|
||||
client.setHostnameVerifier(this.hostnameVerifier);
|
||||
}
|
||||
Request.Builder builder = new Request.Builder().url(uri());
|
||||
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
|
||||
for (String v : entry.getValue()) {
|
||||
builder.addHeader(entry.getKey(), v);
|
||||
}
|
||||
}
|
||||
final Request request = builder.build();
|
||||
wsCall = WebSocketCall.create(client, request);
|
||||
wsCall.enqueue(new WebSocketListener() {
|
||||
@Override
|
||||
public void onOpen(com.squareup.okhttp.ws.WebSocket webSocket, Response response) {
|
||||
ws = webSocket;
|
||||
final Map<String, List<String>> headers = response.headers().toMultimap();
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.emit(EVENT_RESPONSE_HEADERS, headers);
|
||||
self.onOpen();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(BufferedSource payload, final PayloadType type) throws IOException {
|
||||
Object data = null;
|
||||
switch (type) {
|
||||
case TEXT:
|
||||
data = payload.readUtf8();
|
||||
break;
|
||||
case BINARY:
|
||||
data = payload.readByteArray();
|
||||
break;
|
||||
default:
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.onError("Unknown payload type: " + type, new IllegalStateException());
|
||||
}
|
||||
});
|
||||
}
|
||||
payload.close();
|
||||
final Object finalData = data;
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
if (finalData == null) {
|
||||
return;
|
||||
}
|
||||
if (finalData instanceof String) {
|
||||
self.onData((String) finalData);
|
||||
} else {
|
||||
self.onData((byte[]) finalData);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onPong(Buffer payload) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onClose(int code, String reason) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.onClose();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onFailure(final IOException e, final Response response) {
|
||||
EventThread.exec(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.onError("websocket error", e);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
client.getDispatcher().getExecutorService().shutdown();
|
||||
}
|
||||
|
||||
protected void write(Packet[] packets) {
|
||||
final WebSocket self = this;
|
||||
this.writable = false;
|
||||
for (Packet packet : packets) {
|
||||
Parser.encodePacket(packet, new Parser.EncodeCallback() {
|
||||
@Override
|
||||
public void call(Object packet) {
|
||||
try {
|
||||
if (packet instanceof String) {
|
||||
self.ws.sendMessage(TEXT, new Buffer().writeUtf8((String) packet));
|
||||
} else if (packet instanceof byte[]) {
|
||||
self.ws.sendMessage(BINARY, new Buffer().write((byte[]) packet));
|
||||
}
|
||||
} catch (IOException e) {
|
||||
logger.fine("websocket closed before onclose event");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
final Runnable ondrain = new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
self.writable = true;
|
||||
self.emit(EVENT_DRAIN);
|
||||
}
|
||||
};
|
||||
|
||||
// fake drain
|
||||
// defer to next tick to allow Socket to clear writeBuffer
|
||||
EventThread.nextTick(ondrain);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void onClose() {
|
||||
super.onClose();
|
||||
}
|
||||
|
||||
protected void doClose() {
|
||||
if (wsCall != null) {
|
||||
wsCall.cancel();
|
||||
}
|
||||
if (ws != null) {
|
||||
try {
|
||||
ws.close(1000, "");
|
||||
} catch (IOException e) {
|
||||
// websocket already closed
|
||||
} catch (IllegalStateException e) {
|
||||
// websocket already closed
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected String uri() {
|
||||
Map<String, String> query = this.query;
|
||||
if (query == null) {
|
||||
query = new HashMap<String, String>();
|
||||
}
|
||||
String schema = this.secure ? "wss" : "ws";
|
||||
String port = "";
|
||||
|
||||
if (this.port > 0 && (("wss".equals(schema) && this.port != 443)
|
||||
|| ("ws".equals(schema) && this.port != 80))) {
|
||||
port = ":" + this.port;
|
||||
}
|
||||
|
||||
if (this.timestampRequests) {
|
||||
query.put(this.timestampParam, String.valueOf(new Date().getTime()));
|
||||
}
|
||||
|
||||
String _query = ParseQS.encode(query);
|
||||
if (_query.length() > 0) {
|
||||
_query = "?" + _query;
|
||||
}
|
||||
|
||||
return schema + "://" + this.hostname + port + this.path + _query;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user