Websocket连接握手超时

时间:2016-03-21 03:18:13

标签: java scala websocket playframework-2.3

public static WebSocket<JsonNode> chat(final String chatname, final String username) {
    Logger.info("Received request for WebSocket");
    return new WebSocket<JsonNode>() {
        public void onReady(WebSocket.In<JsonNode> in, final WebSocket.Out<JsonNode> out){
            ......
            //My Code never reaches here
        }
}

我看到日志条目“收到Websocket请求”,然后它永远不会点击onReady。

播放版本2.3.10和Scala版本2.11.6。

直截了当的Javascript代码

var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var chatSocket = new WS("@routes.Application.chat(chatname, username).webSocketURL(request)")

有人能指出我正确的方向吗?有一些版本不匹配问题导致异常和JVM提前退出,我能够清除所有这些,但这个没有提供任何线索。

Chrome控制台显示错误“握手超时”

编译:: scala编译后的Javascript

$(function() {

$("#onChat").show()

var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var chatSocket = new WS("ws://localhost:9000/room/chat?chatname=topic&amp;username=test")

var sendMessage = function() {
    chatSocket.send(JSON.stringify(
        {text: $("#talk").val()}
    ))
    $("#talk").val('')
}

var receiveEvent = function(event) {
    var data = JSON.parse(event.data)

    // Create the message element
    var el = $('<div class="message"><span></span><p></p></div>')
    $("span", el).text(data.user)
    $("p", el).text(data.message)
    $(el).addClass(data.kind)
    $('#messages').append(el)
}

var handleReturnKey = function(e) {
    if(e.charCode == 13 || e.keyCode == 13) {
        e.preventDefault();
        waitForSocketConnection(chatSocket,sendMessage);
    }
}

$("#talk").keypress(handleReturnKey)

chatSocket.onmessage = waitForSocketConnection(chatSocket,receiveEvent);

// Make the function wait until the connection is made...
function waitForSocketConnection(socket, callback) {
    setTimeout(function () {
        if (socket.readyState === 1) {
            console.log("Connection is made")
            if(callback != null) {
                callback();
            }
            return;
        } else {
            console.log("wait for connection...")
            waitForSocketConnection(socket, callback);
        }

    }, 1000); // wait 5 milisecond for the connection...
}

})

路线

GET     /                                controllers.Application.index()
GET     /room                          controllers.Application.chatRoom(chatname: String ?= null, username: String ?= null)
GET     /room/chat                       controllers.Application.chat(chatname, username)
GET     /assets/javascripts/chatroom.js  controllers.Application.chatRoomJs(chatname, username)

# Map static resources from the /public folder to the /assets URL path
GET     /assets/*file                    controllers.Assets.at(path="/public", file)

1 个答案:

答案 0 :(得分:0)

后端

控制器 - Java 8

import play.mvc.WebSocket;

public static WebSocket<String> socket() {
    return WebSocket.withActor(MyWebSocketActor::props);
}

控制器 - Java 7

public static WebSocket<String> socket() {
    return WebSocket.withActor(new Function<ActorRef, Props>() {
        public Props apply(ActorRef out) throws Throwable {
            return MyWebSocketActor.props(out);
        }
    });
}

演员 - 处理程序

import akka.actor.*;

public class MyWebSocketActor extends UntypedActor {

    public static Props props(ActorRef out) {
        return Props.create(MyWebSocketActor.class, out);
    }

    private final ActorRef out;

    public MyWebSocketActor(ActorRef out) {
        this.out = out;
    }

    public void onReceive(Object message) throws Exception {
        if (message instanceof String) {
            out.tell("I received your message: " + message, self());
        }
    }
}

来源link

前端

jQuery https://github.com/ffdead/jquery-graceful-websocket

<强>的Javascript : 这就是我们在这里使用的模式:

<!DOCTYPE html>
  <meta charset="utf-8" />
  <title>WebSocket Test</title>
  <script language="javascript" type="text/javascript">

  var wsUri = "ws://YOUR_URL"; // it should be wss:// for https connections
  var output;

  function init()
  {
    output = document.getElementById("output");
    testWebSocket();
  }

  function testWebSocket()
  {
    websocket = new WebSocket(wsUri);
    websocket.onopen = function(evt) { onOpen(evt) };
    websocket.onclose = function(evt) { onClose(evt) };
    websocket.onmessage = function(evt) { onMessage(evt) };
    websocket.onerror = function(evt) { onError(evt) };
  }

  function onOpen(evt)
  {
    writeToScreen("CONNECTED");
    doSend("WebSocket rocks");
  }

  function onClose(evt)
  {
    writeToScreen("DISCONNECTED");
  }

  function onMessage(evt)
  {
    writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data+'</span>');
    websocket.close();
  }

  function onError(evt)
  {
    writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data);
  }

  function doSend(message)
  {
    writeToScreen("SENT: " + message);
    websocket.send(message);
  }

  function writeToScreen(message)
  {
    var pre = document.createElement("p");
    pre.style.wordWrap = "break-word";
    pre.innerHTML = message;
    output.appendChild(pre);
  }

  window.addEventListener("load", init, false);

  </script>

  <h2>WebSocket Test</h2>

  <div id="output"></div>