大多数在线示例,包括official one要求在服务器端设置以下内容:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
这在客户端:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
因此,这使用相同的服务器来服务 index.html
以及处理套接字连接,它看起来像 sockets.io在服务器上的 socket.io
目录下创建一个 socket.io
js 文件。到目前为止一切都很好。
现在,我正在开发 cordova应用程序中,我现在不必从服务器提供 index
文件,因为它将与应用程序捆绑在一起。我只需要连接到本地计算机上特定端口上运行的套接字服务器。
另外,我不想使用express,因为我正在学习 - 我认为简单地设置套接字服务器不需要它,我宁愿在不了解它的作用或它如何使我的生活更轻松(换句话说,在进入 jquery 世界之前,我宁愿了解一两点关于 javascript 的知识...)。
所以我在 server.js 文件中尝试了以下操作:
var port = 80;
io = require('socket.io')(port);
console.log('socket server started @ %s !', port);
通过node server.js
命令执行此命令会打印socket server started @ 80!
根据documentation应该创建一个监听端口 80
的 http
服务器(可能通过 socket.io 进行了一些很棒的增强)。
现在,如果我通过括号 IDE 在 http://127.0.0.1:56958/启动的
其中包含以下内容:node.js
服务器加载 index.html
...path/index.html
<script src="scripts/libs/socket.io/socket.io.js"></script>
<script>
console.log('test');
var socket = io('http://127.0.0.1:80');
</script>
(其中 scripts/libs/socket.io/socket.io.js
是独立的 sockets.io
客户端库,我从他们的 github repo 下载)
这让我在最新版本的 chrome 中出现以下错误:
Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'". Either the 'unsafe-inline' keyword, a hash ('sha256-2j6JUXRmZBJXdmMDTRd3ZxygBJNrb8gSbgOi4FOjiy0='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
我还尝试使用 file:///
协议(protocol)从文件系统加载 index.html
文件,这会引发相同的错误。
我做错了什么,如何解决这个问题?
注:我见过this问题,但我没有 cordova.xml
文件,因为我还没有使用 cordova 来构建应用程序。我尝试启用跨源资源共享(使用商店的扩展),但这也没有帮助。
更新:
下面是目录结构:
root
|_app
| | // lots of cordova directories and files like package.json
| |_www
| |_scripts
| | |_libs
| | |_socket.io
| | |_socket.io.js
| |_index.html
|_node_modules
| |_socket.io
|_server
|_server.js
最佳答案
插件cordova-plugin-whitelist正在阻止您的socket.io连接。可以查看配置详情here 。您需要仔细配置它,但为了测试的目的,您可以允许一切:
<meta http-equiv="Content-Security-Policy" content="default-src *;">
关于javascript - 无法从通过不同服务器或文件系统提供的 html 文件连接到 socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33678772/