5

我已经使用 Scala 2.11 安装了新的 Play Framework 2.3,我将使用 websocket 构建一个应用程序。

使用非常简单的代码使用 scala 的服务器:

object TestWebSocket extends Controller {

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

route.conf 是:GET /wsk/testwebsocket controllers.TestWebSocket.mysocketservice

现在我需要一个 Javascript 代码来将我的页面与 scala 代码连接起来,我可以使用什么 javascript 库?我见过一个 socket.io,但似乎只适用于 node.js 服务器。

我知道我可以直接使用 WebSocket,但我将使用像 socket.io 这样的库来与旧浏览器兼容。

有人能帮我吗?非常感谢

4

3 回答 3

1

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.

于 2014-06-12T20:39:26.720 回答
0

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.

于 2014-06-03T19:09:33.570 回答
0

我使用优雅的 websocket。它非常直观,隐藏了所有复杂性。

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);
}
于 2014-08-12T12:30:41.523 回答