2015-12-04 74 views
2

我正在构建Socket.IO的示例聊天项目(有一些修改),我一直试图让人们连接localhost:3000127.0.0.1:3000,但都没有工作。我错过了什么吗? (如果有一个公然明显的问题,对不起,我吸与联网。)通过LAN托管Socket.io服务器

index.js:

var app=require('express')(); 
var http=require('http').Server(app); 
var io=require('socket.io')(http); 
var chalk=require('chalk'); 

var online=0; 
var prt=process.argv[2]===undefined?3000:process.argv[2]; 

process.stdin.on('data',function(){ 
    var str=String(process.stdin.read()); 
    if(str.search("!quit")){ 
     io.emit('chat message','Console: stopping server.'); 
     process.exit(); 
    } 
}); 

app.get('/',function(req,res){ 
    res.sendFile(__dirname+'/index.html'); 
}); 

io.on('connection',function(socket){ 
    online++; 
    console.log(chalk.green('joined |',chalk.cyan(online),'online')); 

    socket.on('chat message',function(msg){ 
     io.emit('chat message',msg); 
     console.log(chalk.magenta('message |',msg)); 
    }); 

    socket.on('disconnect',function(){ 
     online--; 
     console.log(chalk.red('left |',chalk.cyan(online),'online')); 
    }); 
}); 

http.listen(prt,function(){ 
    console.log(chalk.yellow('SIOChat listening on',chalk.cyan(prt))); 
}); 

的index.html(为便于阅读,省略CSS):

<html> 
    <head> 
     <title>SIOChat</title> 
    </head> 
    <body> 
     <ul id='messages'></ul> 
     <form action=''> 
      <input id='m' autocomplete='off'/><button>Send</button> 
     </form> 
     <script src='https://cdn.socket.io/socket.io-1.2.0.js'></script> 
     <script src='http://code.jquery.com/jquery-1.11.1.js'></script> 
     <script> 
      var socket=io(); 

      var name=prompt('Enter a nickname','Guest'); 

      $('form').submit(function(){ 
       socket.emit('chat message',name+': '+$('#m').val()); 
       $('#m').val(''); 
       return false; 
      }); 

      socket.on('chat message',function(msg){ 
       $('#messages').append($('<li>').text(msg)); 
      }); 
     </script> 
    </body> 
</html> 

回答

5

localhost是您的机器的名称。如果网络上的另一台机器试图连接到localhost,他们将连接到自己的机器。同样,127.0.0.1是所谓的回送地址,并告诉套接字直接连接到您自己的机器(localhost是在大多数情况下实际上解析为127.0.0.1IP地址的主机名)。

网络上的其他机器需要通过IP地址连接到您的机器。

您可以在Linux/OSX上的命令提示符下(在Windows上)或ifconfig上输入ipconfig来查找您的IP地址。

例如,如果您的IP地址为192.168.1.100,那么其他的机器需要使用一个地址连接到你的电脑像192.168.1.100:3000

+2

帝国时代和LAN的Minecraft各方很快教你这个原则。 :) – TheHansinator