我建立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)));
});
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>
localhost
是您自己的机器的名称。如果网络上的另一台计算机尝试连接localhost
,则它们将连接到自己的计算机。同样,127.0.0.1
这就是所谓的环回地址,它告诉套接字直接连接到您自己的计算机(在大多数情况下localhost
,主机名实际上可以解析为127.0.0.1
ip地址)。
网络上的其他计算机将需要通过IP地址连接到您的计算机。
您可以通过ipconfig
在命令提示符下(在Windows上)或ifconfig
Linux / OSX上键入来查找IP地址。
例如,如果您的IP地址是192.168.1.100
,则其他计算机将需要使用类似以下的地址连接到您的计算机192.168.1.100:3000
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句