2
我正在構建Socket.IO的示例聊天項目(有一些修改),我一直試圖讓人們連接localhost:3000
和127.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>
帝國時代和LAN的Minecraft各方很快教你這個原則。 :) – TheHansinator