您可以访问会话:
package controllers
import play.api._
import play.api.mvc._
import play.api.libs.iteratee._
object Application extends Controller {
def index = Action {
Ok(views.html.index()).withSession("connected" -> "user@gmail.com")
}
//I used for views.html.index the html markup from http://www.websocket.org/echo.html
def wstest = WebSocket.using[String] { request =>
val in = Iteratee.consume[String]()
val username = request.session.get("connected").getOrElse("missing username")
val out = Enumerator("Hello " + username) //puts Hello user@gmail.com on the screen
(in, out)
}
}
好的,现在对于 Java(控制器中的方法):
public static WebSocket<String> chat(){
final Http.Session session = session();
final String name = session("username");//better version
return new WebSocket<String>() {
public void onReady(WebSocket.In<String> in, WebSocket.Out<String> out) {
in.onMessage(new F.Callback<String>() {
public void invoke(String event) {
System.out.println(event);
}
});
in.onClose(new F.Callback0() {
public void invoke() {
System.out.println("Disconnected");
}
});
out.write("Hello " + session.get("username"));
out.write("Hello " + name);
}
};
}
似乎您无法在 websocket 创建中直接访问 http 上下文,但您可以将会话或来自 cookie 的更好数据存储在常量中,并在 WebSocket 实例创建中使用它。
我上传了一个带有测试https://github.com/schleichardt/stackoverflow-answers/tree/so12879547的 Java 示例(它不在 master 分支上)。
PS:这在 WebSocket 创建中不起作用:
Http.Context.current().session().get("username")