use of com.sksamuel.gwt.websockets.Websocket in project Mindustry by Anuken.
the class WebsocketClient method connect.
@Override
public void connect(String ip, int port) {
socket = new Websocket("ws://" + ip + ":" + webPort);
socket.addListener(new WebsocketListener() {
public void onMessage(byte[] bytes) {
try {
ByteBuffer buffer = ByteBuffer.wrap(bytes);
byte id = buffer.get();
if (id != -2) {
// ignore framework messages
Class<?> type = Registrator.getByID(id);
Packet packet = (Packet) ClassReflection.newInstance(type);
packet.read(buffer);
Net.handleClientReceived(packet);
}
} catch (ReflectionException e) {
throw new RuntimeException(e);
}
}
@Override
public void onClose() {
Disconnect disconnect = new Disconnect();
Net.handleClientReceived(disconnect);
}
@Override
public void onMessage(String msg) {
onMessage(Base64Coder.decode(msg));
}
@Override
public void onOpen() {
Connect connect = new Connect();
Net.handleClientReceived(connect);
}
});
socket.open();
}
use of com.sksamuel.gwt.websockets.Websocket in project Mindustry by Anuken.
the class WebsocketClient method pingHost.
@Override
public void pingHost(String address, int port, Consumer<Host> valid, Consumer<Exception> failed) {
try {
if (!Platform.instance.canJoinGame()) {
failed.accept(new IOException());
} else {
Websocket socket = new Websocket("ws://" + address + ":" + webPort);
final boolean[] accepted = { false };
socket.addListener(new WebsocketListener() {
@Override
public void onClose() {
if (!accepted[0])
failed.accept(new IOException("Failed to connect to host."));
}
@Override
public void onMessage(String msg) {
byte[] bytes = Base64Coder.decode(msg);
Host host = NetworkIO.readServerData(address, ByteBuffer.wrap(bytes));
if (bytes.length != 128)
valid.accept(new Host("Unknown", address, "Unknown", 0, 0, 0));
else
valid.accept(host);
accepted[0] = true;
socket.close();
}
@Override
public void onOpen() {
socket.send("ping");
}
});
socket.open();
Timers.runTask(60f * 5, () -> {
if (!accepted[0]) {
failed.accept(new IOException("Failed to connect to host."));
socket.close();
}
});
}
} catch (Exception e) {
failed.accept(new IOException("Failed to connect to host."));
}
}
Aggregations