Created
March 29, 2013 04:46
-
-
Save kamekoopa/5268800 to your computer and use it in GitHub Desktop.
社内LT用資料
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
package controllers; | |
import java.util.HashMap; | |
import java.util.Map; | |
import play.libs.F.Callback; | |
import play.libs.F.Callback0; | |
import play.mvc.Controller; | |
import play.mvc.WebSocket; | |
import play.mvc.WebSocket.Out; | |
public class Application extends Controller { | |
/** idとoutをペアにして保存したり、メッセージをブロードキャストする自作クラス */ | |
static final Outputs outputs = new Outputs(); | |
public static WebSocket<String> ws(final int id){ | |
return new WebSocket<String>(){ | |
@Override | |
public void onReady(In<String> in, Out<String> out) { | |
/* ---- ↓接続が開かれた時の処理↓ ---- */ | |
// 接続が開かれたらhelloメッセージ送って、idとoutをペアにして保存 | |
outputs.sayToEveryOne("id : " + id + " さんインしたお"); | |
outputs.store(id, out); | |
/* ---- ↑接続が開かれた時の処理↑ ---- */ | |
/* ---- ↓クライアントからメッセージを送られた時の処理↓ ---- */ | |
in.onMessage(new Callback<String>() { | |
@Override | |
public void invoke(String message) throws Throwable { | |
//接続中のみんな(自分含む)にメッセージを送る | |
outputs.sayToEveryOne(message); | |
} | |
}); | |
/* ---- ↑クライアントからメッセージを送られた時の処理↑ ---- */ | |
/* ---- ↓クライアントから切断された時の処理↓ ---- */ | |
in.onClose(new Callback0() { | |
@Override | |
public void invoke() throws Throwable { | |
//保存してある出力を削除してさよならメッセージ | |
outputs.remove(id); | |
outputs.sayToEveryOne("id : " + id + " さんが死にました"); | |
} | |
}); | |
/* ---- ↑クライアントから切断された時の処理↑ ---- */ | |
} | |
}; | |
} | |
/** | |
* IDとOutをペアにして管理するクラス | |
*/ | |
private static class Outputs { | |
/** idとOutのMap */ | |
private final Map<Integer, Out<String>> outputs = new HashMap<Integer, Out<String>>(); | |
void store(int id, Out<String> out){ | |
outputs.put(Integer.valueOf(id), out); | |
} | |
void remove(int id){ | |
Integer key = Integer.valueOf(id); | |
if(outputs.containsKey(key)){ | |
outputs.remove(key); | |
} | |
} | |
void sayToEveryOne(String message){ | |
for (Out<String> out : outputs.values()){ | |
out.write(message); | |
} | |
} | |
} | |
} |
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
# Routes | |
# This file defines all application routes (Higher priority routes first) | |
# ~~~~ | |
# Home page | |
GET /ws controllers.Application.ws(id:Int) | |
# Map static resources from the /public folder to the /assets URL path | |
GET /assets/*file controllers.Assets.at(path="/public", file) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment