閲覧者表示

はじめに

Ajax を使ってリアルタイムに現在の閲覧者を表示するCGIです。
30秒毎に現在の状況を更新し、変更があった場合には文字が赤く変化します。

スタート

JavaScript

ajaxの検索結果を見て適当に作りました。
30秒事にリクエストを送って、変化があるかどうかの場合わけをしています。

var xmlhttp;
var count = 0;

function check()
{
    var o = document.getElementById( "disp" );
    if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
    {
        if( count == parseInt( xmlhttp.responseText ) )
        {
            o.style.color = o.parentElement.style.color;
        }
        else
        {
            count = parseInt( xmlhttp.responseText );
            o.innerHTML = count;
            o.style.color = 'red';
        }
    }
}
function getVisitor()
{
    setTimeout( "getVisitor()", 30*1000 );
    /*@cc_on
    @if( @_jscript_version >= 5 )
        try
        {
            xmlhttp = new ActiveXObject( "Msxml2.XMLHTTP" );
        }
        catch( e )
        {
            try
            {
                xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );
            }
            catch( E )
            {
                xmlhttp = false;
            }
        }
    @else
        xmlhttp = false;
    @end @*/
    if( !xmlhttp )
    {
        xmlhttp = new XMLHttpRequest();
    }
    
    if( xmlhttp )
    {
        xmlhttp.onreadystatechange = check;
        xmlhttp.open( 'GET', './visitor.cgi', true );
        xmlhttp.send( null );
    }
}

visitor.cgi

CGI入門レベルの簡単なCGIです。
REMOTE_HOSTで判断し、10秒の余裕を見て40秒以上経っているデータは削除しています。

#!/usr/bin/ruby -Ke

require 'cgi'
cgi = CGI.new()

count = 0
File.open( "visitor.txt", "r+" ) do |file|
    file.flock( File::LOCK_EX )
    now = Time.now.to_i
    exist = false
    str = ""
    file.each do |line|
        ip, time = line.chomp.split( /\t/ )
        if ip == cgi.remote_addr
            time = now
            exist = true
        end
        
        if time.to_i < now - 40
        else
            count += 1
            str += [ ip, time, "\n" ].join( "\t" )
        end
    end
    if !exist
        count += 1
        str += [ cgi.remote_addr, now, "\n" ].join( "\t" )
    end
    file.rewind
    file.truncate( 0 )
    file.write str
end

print "Content-Type: text/plain\n"
print "Pragma: no-cache\n"
print "Cache-Control: no-cache\n"
print "Expires: Thu, 01 Dec 1994 16:00:00 GMT\n\n"
print count.to_s

スポンサード リンク

トラックバック

トラックバックURL
https://linux-life.net/tb/program/ruby/cgidoc/visitor/
Linux Life 〜 No linux, No life 〜
プログラミング > Ruby > CGI入門 > 閲覧者表示