Last active
August 29, 2015 14:22
-
-
Save ctipper/5a66b08b7a22afc24a8b to your computer and use it in GitHub Desktop.
Websocket onMessage with a callback and then using JDK 8 CompletableFuture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface Callback<T> { | |
public void call(T value); | |
} | |
import java.io.Console; | |
public class ConsoleTask implements Runnable { | |
Console console; | |
private final Callback<String> callback; | |
public ConsoleTask(Callback<String> callback) { | |
this.callback = callback; | |
} | |
@Override | |
public void run() { | |
console = System.console(); | |
if (console == null) { | |
callback.call("No console."); | |
} | |
String msg = console.readLine(); | |
callback.call(msg); | |
} | |
} | |
@OnMessage | |
public void onMessage(Session session, Message message) { | |
System.out.println("Received: '" + message.getMessage() + "'"); | |
if (latch.getCount() == 0) { | |
latch = new CountDownLatch(1); | |
executor.execute(new ConsoleTask(new Callback<String>() { | |
@Override | |
public void call(String msg) { | |
try { | |
session.getBasicRemote().sendObject(new Message(writeJson(msg))); | |
} catch (IOException | EncodeException e) { | |
logger.debug(e.getMessage()); | |
} | |
latch.countDown(); | |
} | |
})); | |
} | |
System.out.print("Enter a message: "); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.Console; | |
import java.util.function.Supplier; | |
public class ConsoleTask<T> implements Supplier<String> { | |
Console console; | |
@Override | |
public String get() { | |
console = System.console(); | |
if (console == null) { | |
return "No console."; | |
} | |
String msg = console.readLine(); | |
return msg; | |
} | |
} | |
@OnMessage | |
public void onMessage(Session session, Message message) { | |
System.out.println("Received: '" + message.getMessage() + "'"); | |
if (latch.getCount() == 0) { | |
latch = new CountDownLatch(1); | |
ConsoleTask<String> task = new ConsoleTask<String>(); | |
CompletableFuture.supplyAsync(task, executor).thenAcceptAsync(msg -> { | |
try { | |
session.getBasicRemote().sendObject(new Message(writeJson(msg))); | |
} catch (IOException | EncodeException e) { | |
logger.debug(e.getMessage()); | |
} | |
latch.countDown(); | |
}, executor); | |
} | |
System.out.print("Enter a message: "); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment