---
title: "使用Blazeds中的StreamingAMFChannel通道进行通讯"
author: "jenfee"
date: "2010-04-07T22:11:14Z"
tags: ["Firefox", "Flex", "Servlet", "XML", "thread"]
categories: ["Web前端"]
slug: "blazeds-streamingamfchannel"
draft: false
lastmod: "2010-04-07T22:11:14Z"
id: 636715
url: "https://jenfee.iteye.com/blog/636715"
---

今天在网上看到一遍通过Blazeds中的StreamingAMFChannel通过进行通讯的方法。非常喜欢，特记录下来以备以后使用。

  这个方法是首先建立一个Servlet程序，如下例所示：  
   
import java.io.IOException;    
import java.math.BigDecimal;    
import java.util.Date;    
   
import javax.servlet.ServletException;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;     
   
import flex.messaging.MessageBroker;    
import flex.messaging.messages.AsyncMessage;    
import flex.messaging.util.UUIDUtils;    
   
public class TickCacheServlet extends HttpServlet {    
   
    private static FeedThread thread;    
   
    @Override   
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)    
            throws ServletException, IOException {    
   
        String cmd = req.getParameter("cmd");    
        if (cmd.equals("start")) {    
            start();    
        }    
        if (cmd.equals("stop")) {    
            stop();    
        }    
    }    
   
    @Override   
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)    
            throws ServletException, IOException {    
        // TODO Auto-generated method stub    
        super.doGet(req, resp);    
    }    
   
    @Override   
    public void destroy() {    
        // TODO Auto-generated method stub    
        super.destroy();    
    }    
   
    @Override   
    public void init() throws ServletException {    
        // TODO Auto-generated method stub    
        super.init();    
    }    
   
    public void start() {    
        if (thread == null) {    
            thread = new FeedThread();    
            thread.start();    
        }    
        System.out.println("start!!");    
    }    
   
    public void stop() {    
        thread.running = false;    
        thread = null;    
    }    
   
    public static class FeedThread extends Thread {    
   
        public boolean running = true;    
   
        public void run() {    
            MessageBroker msgBroker = MessageBroker.getMessageBroker(null);    
            String clientID = UUIDUtils.createUUID();    
            int i = 0;    
            while (running) {     
                UserDto user = new UserDto ();     
                user.setId(1);  
                user.setName("test");  
                user.setDept("财务部")

                user.setCreateDate(new Date());     
   
                System.out.println(i);    
   
                AsyncMessage msg = new AsyncMessage();    
                msg.setDestination("user\_Tun");    
                msg.setHeader("DSSubtopic", "user");    
                msg.setClientId(clientID);    
                msg.setMessageId(UUIDUtils.createUUID());    
                msg.setTimestamp(System.currentTimeMillis());    
                msg.setBody(user);    
                msgBroker.routeMessageToService(msg, null);    
                i++;    
                try {    
                    Thread.sleep(20);    
                } catch (InterruptedException e) {    
                }    
   
            }    
        }    
    }    
   
} 

 

2。设置services-config.xml，在其中加入:

&lt;channel-definition id="my-streaming-amf" class="mx.messaging.channels.StreamingAMFChannel"&gt;  
            &lt;endpoint url="[http://{server.name}:{server.port}/{context.root}/messagebroker/streamingamf](http://%7Bserver.name%7D:%7Bserver.port%7D/%7Bcontext.root%7D/messagebroker/streamingamf)" class="flex.messaging.endpoints.StreamingAMFEndpoint"/&gt;  
            &lt;properties&gt;  
                &lt;idle-timeout-minutes&gt;0&lt;/idle-timeout-minutes&gt;  
                &lt;max-streaming-clients&gt;10&lt;/max-streaming-clients&gt;  
                &lt;server-to-client-heartbeat-millis&gt;5000&lt;/server-to-client-heartbeat-millis&gt;  
                &lt;user-agent-settings&gt;  
                    &lt;user-agent match-on="MSIE" kickstart-bytes="2048" max-streaming-connections-per-session="1"/&gt;  
                    &lt;user-agent match-on="Firefox" kickstart-bytes="2048" max-streaming-connections-per-session="1"/&gt;  
                &lt;/user-agent-settings&gt;  
            &lt;/properties&gt;  
        &lt;/channel-definition&gt;

 

messaging-config.xml文件中，加入如下：  
    &lt;destination id="user\_Tun"&gt;  
        &lt;properties&gt;  
            &lt;server&gt;  
                &lt;allow-subtopics&gt;true&lt;/allow-subtopics&gt;  
                &lt;subtopic-separator&gt;.&lt;/subtopic-separator&gt;  
            &lt;/server&gt;  
        &lt;/properties&gt;  
        &lt;channels&gt;  
            &lt;channel ref="my-polling-amf" /&gt;  
            &lt;channel ref="my-streaming-amf" /&gt;  
        &lt;/channels&gt;  
    &lt;/destination&gt;

 

4.Flex执行程序

&lt;?xml version="1.0" encoding="utf-8"?&gt;  
&lt;mx:Application xmlns:mx="[http://www.adobe.com/2006/mxml](http://www.adobe.com/2006/mxml)" layout="absolute" viewSourceURL="srcview/index.html" height="378" width="426"&gt;

    &lt;mx:Script&gt;  
        &lt;![CDATA[  
            import mx.controls.Alert;  
            import mx.rpc.events.ResultEvent;  
            import mx.messaging.Consumer;  
            import mx.messaging.Channel;  
            import mx.messaging.ChannelSet;  
            import mx.messaging.events.MessageEvent;

            \[Bindable]  
            public var user:UserVO;  
             
            public function sendmsg():void  
            {  
                Alert.show("click start");  
                var consumer:Consumer = new Consumer();  
                consumer.destination = "user\_Tun";  
                consumer.subtopic = "user";  
                consumer.channelSet = new ChannelSet(\["my-streaming-amf"]);  
                consumer.addEventListener(MessageEvent.MESSAGE, messageHandler);  
                consumer.subscribe();  
              }  
             
            private function messageHandler(event:MessageEvent):void  
            {  
                var t:UserVO = event.message.body as UserVO;  
                txtName.text = t.name;  
            }  
        ]]&gt;  
    &lt;/mx:Script&gt;  
    &lt;mx:Panel x="32" y="43" width="362" height="302" layout="absolute" &gt;  
        &lt;mx:Label x="72" y="43" text="Label" id="txtName"/&gt;  
        &lt;mx:Button x="132" y="41" label="Button" click="sendmsg(); "/&gt;  
    &lt;/mx:Panel&gt;  
&lt;/mx:Application&gt;

 

----再次感谢这个作者给了一个非常好的思路。文章略有修改。