Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 535
faster2b Avatar asked Nov 11 '22 07:11

faster2b


1 Answers

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.

like image 72
Dario Avatar answered Nov 15 '22 13:11

Dario