Ruby Ruby No Rails --- 简单到脑残的在线聊天

匿名 · 2014年03月17日 · 最后由 liluo 回复于 2014年03月18日 · 3880 次阅读

如题 这是个简单到脑残的在线聊天的 demo。 郑重声明,非原创,只是偶然在gist上看到的。 觉得有趣,略作修改。

预览如下。

代码如下。

require 'sinatra' # gem install sinatra --no-rdoc --no-ri
set :port, 3000
set :environment, :production

html = <<-EOT
<html><head><style>
#text{width:100%; font-size: 15px; padding: 5px; display: block;}
</style></head><body>
    <input id="text" placeholder="Write and Enter."/>
    <div id="chat"></div>
    <script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
    <script>
    $('#text').keypress(function(e){
        if( e.keyCode==13 ){
            $.get('/send',{text:$('#text').val()});
            $('#text').val('');
        }
    });
    last = 0;
    setInterval(function(){
        $.get('/update',{last:last},
            function(response){
                $('#chat').append(response);
                last = $('span[data-last]:last').data('last');
                });
        },1000);
    </script>
</body></html>
EOT

chat = ['welcome..']
get('/') { html }
get '/send' do
    chat << "#{request.ip} : #{params['text']}"
end
get '/update' do
    updates = chat[params['last'].to_i..-1] || chat
    last = "<span data-last=\"#{chat.size}\"></span>"
    if updates.size>0
        updates.join('</br>') + "#{last}</br>"
    end
end

又是五天工作日,想想就桥豆无聊。

占个坑,我也来写一个看看

匿名 #2 2014年03月17日

@bhuztez 没有头像的传说哥。

1s 刷一次,一台服务器能撑到多少个客户端?

匿名 #4 2014年03月17日

#3 楼 @yakczh 和玩具 demo 较什么劲。无聊人在无聊时写的无聊代码。

加上 faye,让你的在线聊天马上好用起来。

-module(index).
-export([main/0, event/1]).
-include_lib("n2o/include/wf.hrl").


main() ->
    #dtl{file="index", app=chat,
         bindings=
             [
              {title, "Chat"},
              {body, body()}
             ]
        }.


body() ->
    {ok,Pid} = wf:comet(fun() -> chat_loop() end),
    [
      #panel{ id=history },
      #textbox{ id=message },
      #button{ id=send, body="Send", postback={message, Pid}, source=[message] }
    ].


event(init) ->
    wf:reg(room),
    wf:insert_bottom(history, [#span{body="OK"}, #br{}]);
event({message, Pid}) ->
    Message = wf:q(message),
    Pid ! {message, Message};
event(_) ->
    ok.


chat_loop() ->
    receive
        {message, Message} ->
            Terms = [ #span { body= Message }, #br{} ],
            wf:insert_bottom(history, Terms),
            wf:flush(room);
        _ ->
            ok
    end,
    chat_loop().

好像加入 ruby 还算 ror 组 以后就会看到这个人发 gist。。。。

月初的时候折腾过 HTML5 Server Sent Event,代码没几行,更简单,而且是 server push 不是 client pull

聊天必须 EM

明明是 sinatra

匿名 #14 2014年03月18日

#13 楼 @liluo 标题写的是 No 不是 On 哈哈

需要 登录 后方可回复, 如果你还没有账号请 注册新账号