简体   繁体   中英

Play Framework 2.3 and javascript websocket client library

I have installed the new Play Framework 2.3 with Scala 2.11, and I will build an application with websocket.

The server with scala in quite simple code:

object TestWebSocket extends Controller {

  def mysocketservice = WebSocket.acceptWithActor[String, String] { request => out =>
    TestSocketActor.props(out)
  }
}

the route.conf is: GET /wsk/testwebsocket controllers.TestWebSocket.mysocketservice

now i need a Javascript code for connect my page with the scala code, what javascript library can I use? I have seen a socket.io, but seems work only with node.js server.

I know than I can use a WebSocket directly, but i will using a library like socket.io for the compatibility with the old browser.

Can someone help me? Thank you very much

try out this javascript. This is the standard way to do it on Chrome, Safari, Mozilla etc.

<script type="text/javascript">
    function WebSocketTest(){
        if ("WebSocket" in window){ 
        var ws = new WebSocket("@routes.controllers.TestWebSocket.mysocketservice().webSocketURL()");
        ws.onopen = function(){
            // Web Socket is connected, send data using send()
            console.log("connected");
            ws.send("Message to send");
        };

        ws.onmessage = function (evt){
            var received_msg = evt.data;
            console.log(evt.data);
        };

        ws.onclose = function(){
            // websocket is closed.
            alert("Connection is closed...");
        };
        }else{
            // The browser doesn't support WebSocket
            alert("WebSocket NOT supported by your Browser!");
        }
    }
WebSocketTest();
</script>

Let me know how it goes.

You don't necessarily need a client side library to take advantage of WebSockets. Mozilla provides solid documentation of the WebSockets API here .

With that said, if you want visitors on older browsers to be able to take advantage of your WebSocket functionality, you may want to look into projects such as SockJS that can gracefully fallback to inferior (but better supported) protocols if need be.

I use graceful websocket. It is very intuitive and hides all the complexity behind.

https://code.google.com/p/jquery-graceful-websocket/

// open socket using standard syntax
ws = $.gracefulWebSocket("ws://localhost:9000/soc"); //use wss for https
ws.onmessage=onSocMsg;

function onSocMsg(event){
  var jsonObj=json.fromString(event.data);
  alert(event.data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM