【发布时间】:2014-01-23 13:27:28
【问题描述】:
我有需要使用实时推送到客户端的 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 服务器和节点)导入它。 js 服务器是同一台服务器。这就是我使用 localhost 的原因)。
问题是,当我调用此模板(从视图中渲染它)并在 chrome 上使用 F12 时,我看到“注意:显示临时标题。”。
我试图在这里检查是什么意思,但我只看到有关 AdBlocks 的讨论,所以我卸载了它,但我仍然收到此错误...
经过更多调查,我发现即使在 apache(本机 HTML 文件)上我也无法获取 js 文件(同样的错误)。
看起来原因是我必须使用 node.js http server (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];
});
});
【问题讨论】:
-
能否请您提供服务器端代码
node.js脚本 -
当您尝试从浏览器访问
http://localhost:8889/socket.io/socket.io.js时得到什么响应? -
服务器位于 AWS(亚马逊)上,因此我的浏览器中的 localhost 将无法正常工作。 SERVER_IP:8889:/socket.io/socket.io.js 给了我 javascript(以“/*!Socket.IO.js build:0.9.16, development. Copyright(c) 2011 LearnBoost
MIT Licensed */”开头)。从服务器本身,使用“curl localhost:8889/socket.io/socket.io.js”我得到相同的 javascript 页面。所以除了 Django 模板之外一切都很好:).. 谢谢! -
那为什么你的模板引用本地主机呢?将其更改为
<script src="http://SERVER_IP:8889/socket.io/socket.io.js"></script> -
我现在会尝试更改它。但我需要机器的内部 IP,而不是外部 IP,对吗?这台机器是附有弹性 IP 的 Amazon EC2 机器。我现在就试一试
标签: javascript django node.js express socket.io