Java – WebSockets, play framework and actor
I need to inform all users about adding new records to the database
> Application. Java – here I put the socket handler method
public WebSocket<JsonNode> sockHandler() {
return WebSocket.withActor(ResponseActor::props);
}
>Then I opened the connection
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var socket = new WS("@routes.Application.sockHandler().webSocketURL(request)")
socket.onmessage = function(event) {
console.log(event);
console.log(event.data);
console.log(event.responseJSON)
}});
>My cast
public class ResponseActor extends UntypedActor {
private final ActorRef out;
public ResponseActor(ActorRef out) {
this.out = out;
}
public static Props props(ActorRef out) {
return Props.create(ResponseActor.class,out);
}
@Override
public void onReceive(Object response) throws Exception {
out.tell(Json.toJson(response),self());
}
}
>Finally, I think I need to call actor from my response controller
public Result addPost() {
Map<String,String[]> request = request().body().asFormUrlEncoded();
Response response = new Response(request);
Map<String,String> validationMap = ResponseValidator.validate(response.responses);
if (validationMap.isEmpty()) {
ResponseDAO.create(response);
ActorRef responseActorRef = Akka.system().actorOf(ResponseActor.props(outRef));
responseActorRef.tell(response,ActorRef.noSender());
return ok();
} else {
return badRequest(Json.toJson(validationMap));
}
}
My question is: what is actorref and where can I get its controller? Can you clarify the logic of sending updates to all clients through a web socket?
Solution
I'm studying a similar problem myself, although in Scala, so I'll see if I can help based on what I've learned so far (I have my own problem after my actor receives a message socket open)
Accepting a websocket connection with an actor is not done through a typical request / response model, such as sending a get request for a page to the server Instead, you need to use play's WebSockets API:
import akka.actor.*;
import play.libs.F.*;
import play.mvc.WebSocket;
public static WebSocket<String> socket() {
return WebSocket.withActor(ResponseActor::props);
}
The play WebSockets documentation should help you better than I do: https://www.playframework.com/documentation/2.4.x/JavaWebSockets
