我的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)
答案 0 :(得分:1)
如果您的服务器位于加载网页的同一主机和端口上,那么您应该可以在客户端中执行此操作:
var socket = io();
它将从加载网页时获取相同的主机/端口,并与之建立socket.io连接。
如果您的socket.io服务器与网页不在同一主机/端口上,那么您可能会遇到一些需要解决的跨域问题。