[英]Socket.io.js not found (node.js + express + socket.io)
[英]socket.io in django template - node.js not service socket.io.js
我有Django应用程序,需要使用实时推送到客户端。
我想使用node.js和socket.io(我知道这是今天最简单的平台...)。
为了实现它,我将socket.io框架代码放在模板上:
{% extends "base.html" %}
{% block content %}
{% if error %}
<div id="error">
<h3>{{ error }}</h3>
</div>
{% endif %}
<div id="reply">
<script src="http://localhost:8889/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:8889');
socket.on('connect', function(){
socket.emit('addOrder', 99, {{ reply_id }});
});
</script>
Thank you for your reply
</div>
{% endblock %}
我的node.js在8889上运行,你可以看到..所以我需要调用“script src”从localhost导入它:8889 / socket.io / socket.io.js(Django服务器和node.js服务器是相同的服务器。这就是我使用localhost的原因)。
问题是,当我调用此模板(从视图中呈现),并在chrome上使用F12时,我看到“注意:显示临时标题。”。
我试着检查一下是什么意思,但我只看到有关AdBlocks的谈话,所以我卸载它,但我仍然得到这个错误...
经过更多调查后,我发现即使在apache(原生HTML文件)上我也无法获取js文件(同样的错误)。
看起来原因是我必须使用node.js http服务器(express)来提供此文件,并且无法从任何其他Web服务器调用它。
有谁知道可能是什么原因或如何解决它?
Node.js服务器代码:
var express = require("express");
var app = express();
var io = require('socket.io').listen(app.listen(8889));
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.get('/menu.css', function (req, res) {
res.sendfile(__dirname + '/menu.css');
});
var branches = {};
ojson = {"count":1,"orders":[{"id":100,"state":"ok"}]};
io.sockets.on('connection', function (socket) {
socket.on('connectBranch', function(branchID) {
//save ID info on the socket
socket.branchID = branchID
// save the socket of the branch by ID
branches[branchID]=socket;
// ask the client to run getAll function with orders JSON
branches[branchID].emit('getAll', ojson);
});
// clear - for test
socket.on('clearOrders', function(branchID) {
branches[branchID].emit('clearOrders');
});
// when the client emits 'addOrder', this listens and executes
socket.on('addOrder', function(branchID, orderID){
console.log(branches);
branches[branchID].emit('addOrder', orderID);
});
// when the user disconnects.. perform this
socket.on('disconnect', function(){
// remove the branch from global branches list
delete branches[socket.branchID];
});
});
除非您在localhost
上运行此操作
<script src="http://localhost:8889/socket.io/socket.io.js"></script>
需要改为
<script src="http://SERVER_IP:8889/socket.io/socket.io.js"></script>
更好的是,如果您的前端HTTP服务器是NGINX或类似的,您可以将对socket.io.js
调用代理到端口8889,然后将您的页面更改为
<script src="/socket.io/socket.io.js"></script>
这种方式你不必指定IP,它将与原始HTML页面来自的那个相同
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.