Javascript WebSocket 的错误 url 方案
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13624952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Wrong url scheme for WebSocket
提问by agilesteel
I have a websockets program in play 2.1, which works just fine and the template looks like this:
我在 play 2.1 中有一个 websockets 程序,它工作得很好,模板如下所示:
// Contents of the view.scala.html file
@(userName: String)(implicit request: RequestHeader)
@main("text") {
<script type="text/javascript" charset="utf-8">
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
alert("before")
var socket = new WS("@routes.Application.view(userName).webSocketURL()");
alert("after")
socket.onmessage = function(event) {
alert(event.data);
};
});
</script>
}
The issue is that as soon as I move my javascript into the assets.javascriptsfolder and change the view.scala.htmlfile into the following it stops working.
问题是,一旦我将我的 javascript 移动到assets.javascripts文件夹中并将view.scala.html文件更改为以下文件,它就会停止工作。
// Contents of the view.scala.html file
@(userName: String)(implicit request: RequestHeader)
@main("text") {
<script type="text/javascript" charset="utf-8"
src="@routes.Assets.at("javascripts/viewer.min.js")"></script>
}
Play finds the file, executes the javascript, I can see the popup triggered by the alert("before")line of code, but after that... nothing.
Play 找到文件,执行 javascript,我可以看到由alert("before")代码行触发的弹出窗口,但之后......什么都没有。
This is the google chrome error I get in the console:
这是我在控制台中遇到的谷歌浏览器错误:
Wrong url scheme for WebSocket
http://localhost:9000/@routes.Application.view(userName).webSocketURL()
What am I missing?
我错过了什么?
回答by ThiefMaster
A WebSocket needs ws://or wss://(for SSL) instead of http://.
WebSocket 需要ws://或wss://(对于 SSL)而不是http://.
However, the problem in your code is that the statement @routes.Application.view(userName).webSocketURL()apparently isn't replaced with some useful value but kept as-is. This is because your framework seems to consider assets completely static and thus ignores anything in there that would be a placeholder/variable in a normal template.
但是,您的代码中的问题是该语句@routes.Application.view(userName).webSocketURL()显然没有被一些有用的值替换,而是保持原样。这是因为您的框架似乎认为资产是完全静态的,因此忽略了其中任何可能是普通模板中的占位符/变量的内容。
One possible solution for your problem would be keeping the URL in your template, e.g. by adding data-ws="@....."to your <body>tag and then use JavaScript to extract that attribute:
您的问题的一种可能解决方案是将 URL 保留在您的模板中,例如通过添加data-ws="@....."到您的<body>标签,然后使用 JavaScript 来提取该属性:
var socket = new WebSocket(document.body.getAttribute('data-ws'))
回答by Sid
I used the following :
我使用了以下内容:
ws=new WebSocket("ws://localhost:8080/websocket/wsserver");
ws=new WebSocket("ws://localhost:8080/websocket/wsserver");
Thanks.
谢谢。

