java与flex数据实时交互+blazed

Flex 通过开源的BlazeDS消息服务来支持订阅及发布消息。这个消息服务管理着一些Flex客户端可以订阅或发布的目标地址。Flex提供了 Producer和Consumer这两个组件,让你用来向目标地址发送或订阅消息。如果要订阅消息,你就使用Consumer类的 subscribe()方法。当有消息发送到你订阅了的目标地址时,Consumer上就会触发message事件。

消息传递的目的地址是在你的Flex应用根下一个叫messaging-config.xml中配置的。一个目的地址配置的关键元素是在客户端和服务器交换数据的通道。使用BlazeDS,消息传递的目的地址通常使用流通道或者轮询通道。

1,使用流通道,服务器响应会一直保持开放状态,直到通道连接关闭,这样可以让服务器持续向客户端发送变化的数据。HTTP连接并不是双向的。这意味着一个流 AMF或者HTTP通道实际上需要两个浏览器HTTP连接来完成两个方向上的数据发送。一个用于从服务器向客户端发送流响应,另外一个暂态的连接用在当有数据需要发送到服务器时,从浏览器池中拖拽数据。这个暂态的连接会立即释放回浏览器的连接池中。 2,如果数据没有立刻准备好(长轮询),就可以通过一个简单的时间间隔或者服务器等待时间来配置轮询通道。无论哪种方式,轮询响应都会完成请求。浏览器 HTTP1.1连接缺省是持久的,因此浏览器有可能会重复利用已有的HTTP连接来发送接下来的轮询请求,这样就能减少轮询带来的网络负载。



blazeds推送技术至Flex zz 第一步下载blazeds.war
第二步修改两个配置文件:services-config.xml,messaging-config.xml    services-config.xml加入下面代码  
程序代码    <channel-definition id="my-streaming-amf" class="mx.messaging.channels.StreamingAMFChannel">  <endpoint url="http://{server.name}:{server.port}/{context.root}/messagebroker/streamingamf" class="flex.messaging.endpoints.StreamingAMFEndpoint"/>  <properties>
<idle-timeout-minutes>0</idle-timeout-minutes>
<max-streaming-clients>10</max-streaming-clients>
<server-to-client-heartbeat-millis>5000</server-to-client-heartbeat-millis>
<user-agent-settings>
   <user-agent match-on="MSIE" kickstart-bytes="2048" max-streaming-connections-per-session="1"/>
   <user-agent match-on="Firefox" kickstart-bytes="2048" max-streaming-connections-per-session="1"/>
</user-agent-settings>
</properties>
</channel-definition>     
messaging-config.xml加入下面的代码
  程序代码
  <destination id="tick-data-feed">
<properties>
   <server>
<allow-subtopics>true</allow-subtopics>
<subtopic-separator>.</subtopic-separator>
   </server>
</properties>
<channels>
   <channel ref="my-polling-amf" />
   <channel ref="my-streaming-amf" />
</channels>
</destination>  
第三步:创建一个Servlet:  
程序代码    package cn.bestwiz.design.tc.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 cn.bestwiz.design.tc.Tick;  import flex.messaging.MessageBroker; 
import flex.messaging.messages.AsyncMessage; 
import flex.messaging.util.UUIDUtils;   
public class TickCacheServlet extends HttpServlet {              private static final long serialVersionUID = 1L;     
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.getMessageBrok(null);       
      String clientID = UUIDUtils.createUUID();     
        int i = 0;          
   while (running) {            
     Tick tick = new Tick();               
  tick.setAskPrice(new BigDecimal("100"));                  tick.setBidPrice(new BigDecimal("100"));                  tick.setMidPrice(new BigDecimal("100"));                  tick.setTickTime(new Date());              
tick.setSeqno(String.valueOf(i));
System.out.println(i);               
    AsyncMessage msg = new AsyncMessage();                   msg.setDestination("tick-data-feed");                
msg.setHeader("DSSubtopic", "tick");                 
msg.setClientId(clientID);                 
msg.setMessageId(UUIDUtils.createUUID());                  msg.setTimestamp(System.currentTimeMillis());                  msg.setBody(tick);                 
msgBroker.routeMessageToService(msg, null);                  i++;                 
try {                     
Thread.sleep(20);                 
} catch (InterruptedException e) {
                 }                } 
        }
     } 
  }  
第四步:创建一个Java类:  
程序代码    package cn.bestwiz.design.tc;
   import java.math.BigDecimal; 
import java.util.Date;  
public class Tick {     
private BigDecimal askPrice;       
private BigDecimal bidPrice;       
private BigDecimal midPrice;       
private Date tickTime;      
private String seqno;       
public String getSeqno() {        
return seqno;     
}       
public void setSeqno(String seqno) {
         this.seqno = seqno;      }     
  public BigDecimal getAskPrice() {      
   return askPrice;      }      
public void setAskPrice(BigDecimal askPrice) {          this.askPrice = askPrice;    
}       
public BigDecimal getBidPrice() {        
return bidPrice;      }      
public void setBidPrice(BigDecimal bidPrice) {          this.bidPrice = bidPrice;   
  }      
public BigDecimal getMidPrice() {       
  return midPrice;      }  
     public void setMidPrice(BigDecimal midPrice) {          this.midPrice = midPrice; 
    }      
public Date getTickTime() {      
   return tickTime;      }  

    public void setTickTime(Date tickTime) {  
       this.tickTime = tickTime;   
  }   
}  
第五步:  配置Flex项目:
Root Folder:C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps\blazeds
Root URL:http://localhost:8080/blazeds  Context Root:/blazeds  
第六步:创建AS类:    程序代码   
package cn.sloppy  {    
[RemoteClass(alias="cn.bestwiz.design.tc.Tick")]  
   [Bindable]    
public class Tick      {      
   public function Tick()          {    
     }         
public var askPrice:Number;    
     public var bidPrice:Number;        
public var midPrice:Number;        
public var tickTimeate;;         
public var seqno:String;       
}
}     
第七步:Flex主程序代码  
程序代码     
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 tick:Tick;


public function submsg():void  { 
Alert.show("click start");
var consumer:Consumer = new Consumer(); 
consumer.destination = "tick-data-feed"; 
consumer.subtopic = "tick"; 
consumer.channelSet = new ChannelSet(["my-streaming-amf"]);  consumer.addEventListener(MessageEvent.MESSAGE, messageHandler);  consumer.subscribe();  Alert.show("click end"); 
}              
private function messageHandler(event:MessageEvent):void   { 
var tick:Tick = event.message.body as Tick; 
txtTick.text = tick.seqno; 


<mx:Panel x="524" y="47" width="362" height="302" layout="absolute" title="Watch Tick">
<mx:Label x="72" y="43" text="Label" id="txtTick"/>
<mx:Button x="132" y="41" label="Button" click="submsg(); "/>
</mx:Panel>


第七步:运行Flex:http://localhost:8080/blazeds/HelloWorld-debug/HelloWorld.html?debug=true  点击Button  迂曲运行Servlet:http://localhost:8080/blazeds/TickCacheServlet?cmd=start  再看看Flex的效果:是不是文字一直在增长?  恭喜。成功了。

你可能感兴趣的:(java,应用服务器,浏览器,servlet,Flex)