论坛首页 Ruby版 rails

用 AjaxMessaging 在五分钟内造一个 chat room

浏览 1490 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
时间:2007-07-08
把之前一篇的源碼重整理了一下,作了這個 plugin。



1. 準備

* 下載和安裝 Ruby on Rails
* 下載和安裝 Apache ActiveMQ
* 安裝 Mongrel ( sudo gem install mongrel )
* 安裝 json (sudo gem install json)
* 安裝 stomp (sudo gem install stomp)

2. 產生 chat room 軟件

rails chat


3. 安裝 AjaxMessaging plugin

cd chat
script/plugin install http://ajaxmessaging.googlecode.com/svn/trunk/plugins/ajaxmessaging


4. 設定

a. 設定 Apache ActiveMQ (topic 'chat')
ACTIVEMQ_HOME/conf/activemq.xml
<beans>

  <!-- Allows us to use system properties as variables in this configuration file -->
  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"/>
  
  <broker brokerName="localhost" useJmx="true" xmlns="http://activemq.org/config/1.0">
    <!-- In ActiveMQ 4, you can setup destination policies -->  
    <destinationPolicy>
      <policyMap><policyEntries>        
          <policyEntry topic="chat>">
            <dispatchPolicy>
              <strictOrderDispatchPolicy />
            </dispatchPolicy>
            <subscriptionRecoveryPolicy>
              <lastImageSubscriptionRecoveryPolicy/>
            </subscriptionRecoveryPolicy>
          </policyEntry>
      </policyEntries></policyMap>
    </destinationPolicy>

    <persistenceAdapter>
        <journaledJDBC journalLogFiles="5" dataDirectory="${activemq.base}/activemq-data"/>
    </persistenceAdapter>

    <transportConnectors>
       <transportConnector name="stomp"   uri="stomp://localhost:61613"/>
    </transportConnectors>
    
    <networkConnectors>
      <!-- by default just auto discover the other brokers -->
      <networkConnector name="default-nc" uri="multicast://default"/>
    </networkConnectors>    
  </broker>
</beans>


b. 設定 AjaxMessaging (我們用預設值就可以了)
config/a11g.yml
USERNAME: 
PASSWORD: 
HOST: localhost 
PORT: 61613 
RELIABLE: false 
DEFAULT_CHANNELS: default 
CHANNEL_ROOT: /topic/ 
BASE_URL: /amq 
POLL_DELAY: 0.0 
TIMEOUT: 30


c. 設定資料庫 (我們用 sqlite3)
config/database.yml
development: 
  adapter: sqlite3 
  database: db/dev 
  encoding: utf8 
  timeout: 5000 
 
test: 
  adapter: sqlite3 
  database: db/test 
  encoding: utf8 
  timeout: 5000 
 
production: 
  adapter: sqlite3 
  database: db/prod 
  encoding: utf8 
  timeout: 5000


d. 設定 Mongrel
config/mongrel_conf.yml
:config_script: lib/ajax_messaging_handler.rb


5. 準備 Data Model 和 Scaffold
./script/generate scaffold_resource chat name:string message:string
rake db:migrate


6. 修改 Chat Layout
app/view/layouts/chats.rhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> 
<head> 
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> 
  <title>Chats: <%= controller.action_name %></title> 
  <%= stylesheet_link_tag 'scaffold' %> 
  <%= javascript_include_tag :defaults %> 
  <%= yield :script %> 
</head> 
<body> 
 
<p style="color: green"><%= flash[:notice] %></p> 
 
<%= yield  %> 
 
</body> 
</html>


7. 修改 index view
app/view/chats/index.rhtml
<% content_for("script") do %> 
    <%= a11g_listen_to('chat') %> 
<% end %> 
 
<!-- form to input message --> 
<%= render_component :action => 'new' %> 
 
<!-- message list --> 
<ul id="chat-list"> 
<% for chat in @chats %> 
  <%= render_component :action => 'show', :id => chat.id %> 
<% end %> 
</ul>


8. 修改 new view
app/views/chats/new.rhtml
<% form_remote_for(:chat, :url => chats_path) do |f| %> 
  <%= f.text_field :name %> 
  <%= f.text_field :message %> 
  <%= submit_tag "Talk" %> 
<% end %>


9. 修改 show view 去顯示訊息
app/views/chats/show.rhtml
<li> 
  <%=h @chat.name %> 
  <%=h @chat.message %> 
</li>


10. 修改 chat controller
app/controllers/chats_controller rb
class ChatsController < ApplicationController 
  layout 'chats', :only => 'index' 
 
  def index 
    @chats = Chat.find(:all).reverse 
  end 
  def show 
    @chat = Chat.find(params[:id]) 
  end 
  def create 
    @chat = Chat.create(params[:chat]) 
 
    # create HTML string to show a message 
    content = render_component_as_string :action => 'show', :id => @chat.id 
 
    # create JS string to add a message on list 
    javascript = render_to_string :update do |page| 
      page.insert_html :top, 'chat-list', content 
    end 
 
    AjaxMessaging.send_data 'chat', javascript 
     
    # nothing is rendered 
    render :nothing => true 
  end 
end


11. 啟動伺服器

a. 啟動 ActiveMQ :

cd apache-activemq
./bin/activemq


b. 啟動 Mongrel

cd chat
mongrel_rails start –C ./config/mongrel_conf.rb


c. 開始 Chat
開啟瀏覽器瀏覽http://localhost:3000/chats,你的訊息會即時被其他在這 chat room的人看到。有些瀏覽器限制了同一個網站的連線數目 (如 Firefox) ,想在同一電腦跟自己 chat ,請用兩個不同的 browser。

Credit: 這個教學來自 shooting_star 的相同教學。如果你需要完整、強大又穩定的 comet server,大概你需要的是 shooting_star。

相關連結:
* 原文:用 AjaxMessaging 在五分鍾內造一個 chat room
* 有關這個 chat room 的原理,請讀 Ruby on Rails + AJAX + Mongrel + JMS/MQ/MOM = 即時通訊
* AjaxMessaging Project Home Page
   
论坛首页 Ruby版 rails

跳转论坛:
JavaEye推荐