![](/img/trans.png)
[英]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.