Val*_*rie 2 javascript node.js socket.io
我建立Socket.IO的例子聊天项目(含部分变更)和我一直试图让人们既连接localhost:3000和127.0.0.1:3000,但也都在工作.我错过了什么吗?(如果有一个明显的明显问题,抱歉.我很糟糕.)
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)));
});
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
localhost是您自己的机器的名称.如果网络上的另一台计算机尝试连接localhost,则它们将连接到自己的计算机.类似地,127.0.0.1是所谓的环回地址,并告诉套接字直接连接到您自己的机器(在大多数情况下localhost,实际上是解析为127.0.0.1IP地址的主机名).
网络上的其他计算机将需要通过IP地址连接到您的计算机.
您可以通过ipconfig在命令提示符(在Windows上)或ifconfig在Linux/OSX 上键入来查找您的IP地址.
例如,如果您的IP地址是192.168.1.100,则其他计算机将需要使用类似的地址连接到您的计算机192.168.1.100:3000