Flex + blazeds Learning notes (i) Functional principle and configuration example of---blazeds

Source: Internet
Author: User
Tags cdata soap php script static class wsdl

BlazeDS Test Drive contains examples of the main features: Httpservice Web Services remote-object Messaging

Its implementation is based on a servlet called Flex.messaging.MessageBroker. The configuration of various message channels exists in Web-inf/flex/services-config.xml and the 3 XML files it contains. Here's a brief description of these four different features.

Httpservice:

HTTP requests are sent to the server for a typical purpose of obtaining the server-side XML content. Server-side can use any technology: JSP, Servlet, ASP, PHP, etc., as long as the URL within the request can be specified. This is an asynchronous request, and the server returns a result or fault event, which corresponds to success and failure respectively. You can bind the returned results directly to the DataGrid. Using the useproxy property and crossdomain.xml can be accessed across domains, which is one of the ways to resolve the sandbox effect.

Another way is not to httpservice, but to write a JS or php script, using Ajax (XMLHTTP Object) to access the Cross-domain URL. (Off the topic)

Example: in Proxy-config.xml configuration httpservice the URL address to request, which is accessed by the "destination" mapping relationship in the program, such as "catalog" in the example. Binds the XML content returned by J to the <mx:DataGrid> control.

Main.mxml <mx:httpservice id= "SRV" destination= "Catalog" useproxy= "true"/> <mx:datagrid dataprovider= "{ Srv.lastResult.catalog.product} "width=" 100% "height=" 100% "/> <mx:button label=" Get Data "click=" Srv.send () "/ >

Web-inf/flex/proxy-config.xml <destination id= "Catalog" > <properties> <url>/{context.root}/ Testdrive-httpservice/catalog.jsp</url> </properties> </destination> WebService:

You can access the SOAP based Web service, and the objects returned are automatically deserialized into ActionScript objects. Data binding, sandbox issues are the same as Httpservice.

Example: in Proxy-config.xml Configuration WebService the WSDL address to request, the URL is accessed in the program with a "destination" mapping relationship, such as "Ws-catalog" in the example. Binds the returned object to the <mx:DataGrid> control.

Main.mxml <mx:webservice id= "SRV" destination= "Ws-catalog" useproxy= "true" showbusycursor= "true"/> <mx:D Atagrid dataprovider= "{srv.getProducts.lastResult}" width= "100%" height= "100%" > <mx:columns> <mx:d Atagridcolumn datafield= "ProductId" headertext= "Product Id"/> <mx:datagridcolumn "name" datafield= " Name '/> <mx:datagridcolumn datafield= ' price ' headertext= ' price '/> </mx:columns> </mx:DataGrid> <mx:button label= "Get Data" click= "srv.getproducts ()"/>

Proxy-config.xml <destination id= "Ws-catalog" > <properties> <wsdl>http://livecycledata.org/ services/productws?wsdl</wsdl> <soap>*</soap> </properties> <adapter ref= "Soap-proxy"/ > </destination>

Remote-object:

A way for users to directly access objects on the server, the object to be accessed is a Java class, similar to a servlet or JSP, but this part of the remote request is hidden. The returned Java object is automatically deserialized into a ActionScript object and, if not the specified type, becomes a dynamic object. Remote access is also asynchronous, result, or fault events, which correspond to success and failure respectively.

Example: Configure the class name of the remote object in Remoting-config.xml, and use the "destination" mapping relationship in the program to access an example of the class, such as "product" in the example. Binds the returned Java.util.ArrayList object to the <mx:DataGrid> control.

Main.mxml <mx:remoteobject id= "SRV" destination= "product"/> <mx:datagrid "{ Srv.getProducts.lastResult} "width=" 100% "height=" 100% "/> <mx:button label=" Get Data "click=" srv.getproducts () "/>

Remoting-config.xml <destination id= "Product" > <properties> <source> Flex.samples.product.productservice</source> </properties> </destination>

Package flex.samples.product; Import java.util.ArrayList; public class Productservice {public List getproducts () {List List = new ArrayList (); List.add (New Product ("abc")); return list; } public class Product implements Serializable {private int productId; private String name; public Product (int producti D, String name {...} public int GetProductID () {return productId;} public void Setproductid (int productId) {This.produ Ctid = productId; Public String GetName () {return name.} public void SetName (String name) {this.name = name;}}

Messaging

The message itself contains the message header and the message body, the message header is in a fixed format and the content of the message body is free to write. Access to the state machine, distributed embedded system programming will be easy to understand.

The messaging service allows flex clients to publish (Publish) and subscribe to (Subscribe) messages, and, accordingly, the client is called the producer (Producer) and the consumer (Consumer), which is actually sending and receiving messages.

When a message is sent to a subscribed destination (destination), a client's messages event is triggered. Any messages posted will be sent to all subscribers, even producers themselves. If a subscriber only wants to receive a specific message, you can use the Selecor property to specify the filter condition at the time of the subscription, and only messages that meet the criteria will be forwarded by the server. If you want the server to generate a message, you can generate an instance of the Flex.messaging.messages.AsyncMessage class and send it out with Flex.messaging.MessageBroker.

Example: publish a message on the server side. Create a message by creating an infinite loop thread through a JSP or servlet. In the Messaging-config.xml configuration Message Channel (channel), the "destination" mapping relationship is used in the program to access the channel, such as the "feed" in the example.

startfeed.jsp <% try {feed feed = new feed (); Feed.start (); Out.println ("Feed started");} catch (Exception e) {OUT.P Rintln ("A problem occured while starting the feed:" +e.getmessage ());} %>

Feed.java import java.util.*; Import Flex.messaging.MessageBroker; Import Flex.messaging.messages.AsyncMessage; Import Flex.messaging.util.UUIDUtils; public class Feed {private static feedthread thread; public Feed () {} public void Start () {if (thread = = null) {thread = new Feedthread (); Thread.Start (); } public void Stop () {thread.running = false; thread = NULL;} public static class Feedthread extends thread {public B Oolean running = true; public void Run () {Messagebroker msgbroker = Messagebroker.getmessagebroker (null); String ClientID = Uuidutils.createuuid (); Random Random = new Random (); Double initialvalue = 35; Double currentvalue = 35; Double MaxChange = InitialValue * 0.005; while (running) {Double change = maxchange-random.nextdouble () * MaxChange * 2; Double newvalue = CurrentValue + change ; if (CurrentValue < InitialValue + InitialValue * 0.15 && currentvalue > Initialvalue-initialvalue * 0.15) {currentvalue = newvalue;} else {CurrentValue-= Change Asyncmessage msg = new Asyncmessage (); Msg.setdestination ("feed"); Msg.setclientid (ClientID); Msg.setmessageid (Uuidutils.createuuid ()); Msg.settimestamp (System.currenttimemillis ()); Msg.setbody (New Double (CurrentValue)); Msgbroker.routemessagetoservice (msg, NULL); System.out.println ("" + CurrentValue); try {thread.sleep;} catch (Interruptedexception e) {}}}}

Web-inf/flex/messaging-config.xml <destination id= "Feeds" > <!--destination specific channel configuration can be defined if needed <channels> <channel ref= "My-streaming-amf"/> </channels>--> </destination >

Example: A client can publish and subscribe to a message, configure a message destination in Messaging-config.xml, and use the "destination" mapping relationship in the program to access an example of the class, such as "chat" in the example. Note that the true definition of the channel and its endpoints (endpoint) is in Service-config.xml, and messaging-config.xml only refers to them.

<mx:producer id= "Producer" destination= "chat"/> <mx:consumer id= "Consumer" destination= "chat" MessageHandler (event.message) "selector=" Prop1 = ten "/> <mx:Script> <!--[cdata[Import Mx.messaging.messages.AsyncMessage; Import Mx.messaging.messages.IMessage; Private function Send (): void {var message:imessage = new Asyncmessage (); message.headers = new Array (); message.headers[" Prop1 "] = 10; Message.body.chatMessage = Msg.text; Producer.send (message); Msg.text = "";} Private Function MessageHandler (message:imessage): void {Log.text + = Message.body.chatMessage + "/n";}] --> </mx:Script>

Web-inf/flex/messaging-config.xml <destination id= "chat"/>

Web-inf/flex/service-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 "/> </ Channel-definition>

As you can see, messaging includes two broad classes of different message channels. respectively, streaming channel and polling channel, each with some extension types.

With polling channel, you can configure to poll once every once in a while, or you can configure the server to wait on countless times until there is data (long polling). End the connection after the poll response is complete.

When using streaming channel, the server's response is always connected, so that the server can continue to distribute data to the client once it is connected. Because the HTTP connection is not duplex, an AMF or HTTP channel actually requires 2 browser connections, which are used for uplink and downlink data respectively. This second connection is only established when you need to send data to the server, and immediately after it is released. This kind of channel is especially suitable for the application of high real time and client refresh. This pattern effectively reduces the overhead of repeatedly establishing a connection, rather than polling.

IE and Firefox browsers differ in the maximum number of connections per session. If this causes the streaming channel to fail, BlazeDS automatically uses the next connection configured by Messaging-config.xml.

Instance : Defines multiple default channels as backups.

Web-inf/flex/messaging-config.xml <default-channels> <channel ref= "My-streaming-amf"/> <channel ref= "My-polling-amf"/> <channel ref= "Per-client-qos-polling-amf"/> </default-channels>

If you do not configure the message channel in XML, you can also dynamically assign values in ActionScript scripts.

<mx:Script> <!--[cdata[import mx.messaging.channels.StreamingAMFChannel; import Mx.messaging.ChannelSet; Import Mx.messaging.channels.AMFChannel; Import mx.messaging.events.MessageEvent; Import Mx.messaging.messages.AsyncMessage; Import Mx.messaging.messages.IMessage; Private Function Initcomp (): void {var mystreamingamf:amfchannel = new Streamingamfchannel ("My-streaming-amf", ".. /messagebroker/streamingamf "); var mypollingamf:amfchannel = new AMFChannel ("My-polling-amf", ". /messagebroker/amfpolling "); Mypollingamf.pollingenabled = true; Mypollingamf.pollinginterval = 2000; var channelset:channelset = new ChannelSet (); Channelset.addchannel (MYSTREAMINGAMF); Channelset.addchannel (MYPOLLINGAMF); Consumer.channelset = ChannelSet; Producer.channelset = ChannelSet; }]]--> </mx:Script>  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.