Long polling

リアルタイムWebやEvented I/Oやらがホットらしいが、そのあたりの技術トレンドに追いていかれてる感があるので、調べてみた。
まずはLong polling。

http://en.wikipedia.org/wiki/Push_technology

Long polling is a variation of the traditional polling  technique and allows emulation of an information push from a server to a client. With long polling, the client requests information from the server in a similar way to a normal poll. However, if the server does not have any information available for the client, instead of sending an empty response, the server holds the request and waits for some information to be available. Once the information becomes available (or after a suitable timeout), a complete response is sent to the client. The client will normally then immediately re-request information from the server, so that the server will almost always have an available waiting request that it can use to deliver data in response to an event. In a web/AJAX context, long polling is also known as Comet programming.
  • サーバは返すべきものがなければ、コネクションを握りっぱなしにして新しい情報が取得できるまで待つようにする
  • クライアントはサーバからresponse受け取ったら(あるいはtimeoutしたら)すぐに再リクエスト投げるようにする

という仕組みで、サーバからクライアントへのpushを擬似的に実現するのがLong polling(Comet programming)とのこと


実装してみる

YAPC::Asia 2010のkeroyonnさんスライドを元にやってみた。
1秒毎に/cgi-bin/hello.cgiにajaxでリクエスト投げる。

  • クライアント
<html>
<head>
    <script type="text/javascript" src="/js/jquery-1.4.3.min.js"></script>
    <script type="text/javascript">
        $(function long_polling() { 
            $.ajax({
                  type: 'GET',
                  dataType: 'html',
                  url: "/cgi-bin/hello.cgi",
                  timeout: 10000,
                  success: function(html){ $("#result").append(html); },
                  complete: function() { setTimeout(long_polling, 1000) }
             });
            }); 
    </script>
</head>
<body>
    test<br>
    <div id ="result"></div>
</body>
</html>
  • サーバ
#!/usr/bin/perl
print "Content-type: text/html\n\n";
print "Hello! ";

Long pollingの抱える問題

あまり深く理解してるとはいえないけど、ざっとこんなところかしら。

  • 毎回HTTPリクエスト投げるので、無駄が多い
  • プロセスを1つのクライアントが占有する時間が長いので同時接続数に限界

http://www.atmarkit.co.jp/news/analysis/200701/09/c10k.html