Shivam Jaiswal
Shivam Jaiswal

Reputation: 119

How to implement 'Private Chat' module using akka, scala, websockets in play framework?

I have to implement a Chat module to enable privacy chatting b/w users. I have to do this in Play framework using Scala, Akka and java.net.*
I had got several examples over the net which are demonstrating the use of WebSockets but I didn't got any which can help me implementing Chat module using WebSockets. I have the idea of what i have to do but i am totally confused about what should be the structure of the objects, classes and how Should I start.
Please, if anyone can help me for this or refer me a good article, paper which can help me all the way through the implementation. Thankyou.

Upvotes: 2

Views: 1667

Answers (2)

Julien D
Julien D

Reputation: 1267

I did it in Java. This is what I modified from the exemple :

public class ChatRoom extends UntypedActor {


//Added hashmap to keep references to actors (rooms).
// (might be put in another class)
public static HashMap<String,ActorRef> openedChats=new HashMap<String,ActorRef>();

//Added unique identifier to know which room join
final String chatId;


public ChatRoom(String chatId) {
    this.chatId = chatId;
}

public static void join(final User user, final String chatId , WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) throws Exception{
    final ActorRef chatRoom;

    //Find the good room to bind to in the hashmap
    if(openedChats.containsKey(chatId)){
        chatRoom = openedChats.get(chatId);

    //Or create it and add it to the hashmap
    }else{
        chatRoom = Akka.system().actorOf(new Props().withCreator(new UntypedActorFactory() {
              public UntypedActor create() {
                return new ChatRoom(chatId);
              }
            })
        );
        openedChats.put(chatId,chatRoom);
    }

    // Send the Join message to the room
    String result = (String)Await.result(ask(chatRoom,new Join(user.getId()+"", out), 10000), Duration.create(10, SECONDS));

    // ..... Nothing to do in the rest

It's only the main modifications, you also have to adapt javascript and route file

Feel free to ask questions.

Upvotes: 3

Arnaud Gourlay
Arnaud Gourlay

Reputation: 4666

Have a look at the official sample in playframework

https://github.com/playframework/playframework/tree/master/samples/scala/websocket-chat

Upvotes: 2

Related Questions