通过局域网托管Socket.io服务器

Hosting Socket.io Server over LAN

本文关键字:Socket io 服务器 局域网      更新时间:2023-09-26

我正在构建Socket.IO的示例聊天项目(经过一些修改),我一直试图让人们同时连接localhost:3000127.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上)或在Linux/OSX上键入ifconfig来查找您的ip地址。

例如,如果您的ip地址是192.168.1.100,那么其他机器将需要使用类似192.168.1.100:3000 的地址连接到您的计算机