【发布时间】:2014-12-11 22:17:22
【问题描述】:
我的 node.js 服务器在我的本地机器(Windows)上运行和通信。但是当我复制我的项目并尝试在我的在线服务器(Linux)上运行它时,socket.io 不会从服务器到客户端(html 页面)进行通信。我没有收到任何错误,并且 socket.io 已安装在服务器上。 目录是/var/www/lynx.html
我如何引导服务器与客户端通信,以及客户端与服务器连接。我尝试将http:\\localhost 更改为各种类型的东西,例如实际 IP 地址和本地 127.0.0.1
这是我的代码的重要部分。
客户
<script type="text/javascript">
var socket = io.connect('http://localhost');
socket.on('message', function(message){
var obj = jQuery.parseJSON(message);
var htmlStr ='';
服务器
var dgram = require("dgram");
var udpResultsServer = dgram.createSocket("udp4");
var udpTimeServer = dgram.createSocket("udp4");
var http = require('http');
var io = require('socket.io');
var htmlPage;
var jsonResults;
var tempResults = '';
var finalResults = '';
var time = '0.0';
var r = new Array();
/*
************************************
** Get Ip Addresses **
************************************
*/
function getIP(){
var os = require( 'os' );
var networkConfig = os.networkInterfaces( );
var ipList ='';
for (var name in networkConfig) {
networks = networkConfig[name];
for (var name in networks) {
details = networks[name];
if (details['family'] == "IPv4"){
ipList = ipList + details['address'] + " ";
}
}
}
return ipList;
}
/*
************************************
** Web server and sockets.io **
************************************
*/
var htmlPage;
// read html file to serve
fs.readFile('lynx.html', function(error, data){
if (error){
throw error;
}
else{
htmlPage = data;
console.log('Server wrote to lynx.html file');
}
});
// start web server
var htmlServer = http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
console.log('Client Connected ....');
response.end(htmlPage);
});
htmlServer.listen(8000,'127.0.0.1');
console.log("HTML server started on: " + getIP());
// start up socket.io for transmitting data to the web page
var serv_io = io.listen(htmlServer, { log: false });
serv_io.sockets.on('connection', function(socket){
//send data to client
setInterval(function(){
jsonResults = JSON.stringify(r); // convert final array into a json string
socket.send(jsonResults); // sent json results via socket
console.log('send <--> receive');
}, 1000);
});
这些是我在正在处理的驱动器中本地安装 Socket.io 时出现的错误,这会导致错误吗?
我也全局安装了它 -g 并且没有错误。
npm WARN package.json fs@0.0.2 fs is also the name of a node core module.
npm WARN package.json fs@0.0.2 No description
npm WARN package.json fs@0.0.2 No repository field.
npm WARN package.json net@1.0.2 net is also the name of a node core module.
npm WARN package.json net@1.0.2 'repositories' (plural) Not supported. Please pick one as the 'repository' field
npm WARN package.json has-binary-data@0.1.5 No repository field.
socket.io@1.2.1 node_modules/socket.io
âââ debug@0.7.4
âââ has-binary-data@0.1.3 (isarray@0.0.1)
【问题讨论】:
标签: linux node.js socket.io client-server