最も簡単なSocket.ioの例は何ですか? 質問する

最も簡単なSocket.ioの例は何ですか? 質問する

ということで、最近 Socket.io を理解しようとしていますが、私は超優秀なプログラマーではなく、Web で見つけられるほぼすべての例 (何時間も探しました) には、物事を複雑にする余分なものが含まれています。多くの例では、私を混乱させるようなことがたくさん行われ、奇妙なデータベースに接続したり、coffeescript や大量の JS ライブラリを使用したりして、物事を混乱させています。

サーバーが 10 秒ごとにクライアントにメッセージを送信して時刻を伝え、クライアントがそのデータをページに書き込んだり、アラートを表示したりする、非常にシンプルな基本的な機能例を見てみたいです。それから、そこから物事を理解し、DB 接続など必要なものを追加できます。はい、socket.io サイトの例を確認しましたが、うまく機能せず、何をしているのか理解できません。

ベストアンサー1

編集:誰でも優秀な人に相談した方が良いと思いますチャットの例Socket.IO 入門ページにあります。私がこの回答を提供してから、API はかなり簡素化されました。そうは言っても、新しい API に合わせて少しずつ更新された元の回答がここにあります。

インデックス.html

<!doctype html>
<html>
    <head>
        <script src='/socket.io/socket.io.js'></script>
        <script>
            var socket = io();

            socket.on('welcome', function(data) {
                addMessage(data.message);

                // Respond with a message including this clients' id sent from the server
                socket.emit('i am client', {data: 'foo!', id: data.id});
            });
            socket.on('time', function(data) {
                addMessage(data.time);
            });
            socket.on('error', console.error.bind(console));
            socket.on('message', console.log.bind(console));

            function addMessage(message) {
                var text = document.createTextNode(message),
                    el = document.createElement('li'),
                    messages = document.getElementById('messages');

                el.appendChild(text);
                messages.appendChild(el);
            }
        </script>
    </head>
    <body>
        <ul id='messages'></ul>
    </body>
</html>

アプリ

var http = require('http'),
    fs = require('fs'),
    // NEVER use a Sync function except at start-up!
    index = fs.readFileSync(__dirname + '/index.html');

// Send index.html to all requests
var app = http.createServer(function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
});

// Socket.io server listens to our app
var io = require('socket.io').listen(app);

// Send current time to all connected clients
function sendTime() {
    io.emit('time', { time: new Date().toJSON() });
}

// Send current time every 10 secs
setInterval(sendTime, 10000);

// Emit welcome message on connection
io.on('connection', function(socket) {
    // Use socket to communicate with this particular client only, sending it it's own id
    socket.emit('welcome', { message: 'Welcome!', id: socket.id });

    socket.on('i am client', console.log);
});

app.listen(3000);

おすすめ記事