fdimuccio / play2-sockjs

A SockJS server implementation for Play Framework.
Apache License 2.0
62 stars 11 forks source link

Get IP address #23

Closed Flo354 closed 7 years ago

Flo354 commented 7 years ago

Hi,

I was using Atmosphere-Play until now, and I had the possibility to get the IP address of a resource. Is it possible to do the same thing with play2-sockjs ?

Thanks,

fdimuccio commented 7 years ago

What kind of resource?

In a SockJS handler you have access to the request data (such as the client remote address) through the request object.

Flo354 commented 7 years ago

In atmosphere, a socket is called an AtmosphereResource. Could you please provide me a little snippet so I can see how actual we access the request data ?

Thanks,

P.S : I use the java play2-sockjs

fdimuccio commented 7 years ago

The SockJS handler APIs are the same of the standard Play WebSocket handler:

Scala:

// Snippet taken from the sample application `sockjs-chat` in the samples folder
class Application(chatRoom: ChatRoom) extends Controller with SockJSRouter {

  [...]

  /**
    * SockJS handler
    */
  def sockjs = SockJS.acceptOrResult[JsValue, JsValue] { request =>
    // here you can access the request object
    request.getQueryString("username") match {
      case Some(username) => Future.successful(Right(chatRoom.join(username)))
      case _ => Future.successful(Left(BadRequest(Json.obj("error" -> "unknown username"))))
    }
  }
}

Java:

import play.sockjs.SockJS;
import play.sockjs.SockJSRouter;

// SockJSRouter extends play.mvc.Controller so you can access request(), session() and ctx()
// within the sockjs handler. More here https://www.playframework.com/documentation/2.5.x/JavaActions
public class Reject extends SockJSRouter {

    @Override
    public SockJS sockjs() {
        System.out.println("Client connected: " + request().remoteAddress());
        if (session().get("user") != null) {
            return SockJS.withActor(MySockJSActor::props);
        } else {
            return SockJS.reject(forbidden());
        }

    }
}

Hope it helps

Flo354 commented 7 years ago

Oh, nice ! I was trying to get the ip at an other location, so I was getting the error "There is no HTTP context".

Thanks, you can close the issue!

fdimuccio commented 7 years ago

You are welcome