Created
February 10, 2014 21:27
-
-
Save jfarcand/8924503 to your computer and use it in GitHub Desktop.
This file contains 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
@PushEndpoint("/chat/{room}") | |
@Singleton | |
public class ChatResource { | |
private final Logger logger = LoggerFactory.getLogger(ChatResource.class); | |
/** | |
* The client is sending a JSON message which is decoded as Message object. From the Message, we grab the | |
* remote's endpoint userName and create a PrivateTarget. The PrivateTarget will be used when a message | |
* needs to be delivered only to that connection. | |
*/ | |
@OnOpen | |
public PrivateTarget onOpen(RemoteEndpoint r, EventBus eventBus, Message m) { | |
logger.info("OnOpen {}", r); | |
String userName = m.from(); | |
eventBus.encodeToJsonAndFire(String.format("%s connected", userName)); | |
return PrivateTarget.endpoint(userName); | |
} | |
@OnClose | |
public void onClose(RemoteEndpoint r, EventBus eventBus) { | |
logger.info("OnClose {}", r); | |
eventBus.encodeToJsonAndFire(String.format("%s disconnected", r.path())); | |
} | |
@OnMessage(decoders = {JSONDecoder.class}, encoders = {JSONEncoder.class}) | |
public Response onMessage(RemoteEndpoint r, Message message) { | |
logger.info("OnMessage {}", message); | |
return new Response().message(message) | |
.message(String.format("Message will be delivered using %s from %s", r.transport().name(), r.address())); | |
} | |
/** | |
* Return a private message that will be delivered to the appropriate defined PrivateTarget. | |
*/ | |
@OnMessage(decoders = {JSONDecoder.class}) | |
public PrivateResponse onMessage(RemoteEndpoint r, PrivateMessage message) { | |
logger.info("OnMessage {}", message); | |
return PrivateResponse.to(message.to()).message(message); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment