Archive for the ‘Communication between Flex and External Environment’ Category

Flex 4.5 and AmfPhp connection and Data transfer

November 16th, 2011 by aabhaanjan

1

Lets see the other way of data transfer between external environment and the Flex using AMFPHP. Important points regarding AmfPhp ?

1. AMF stands for Action Message Format.

2. It is a binary file that is used to represent a serialized ActionScript object.

3. It was designed to serialize and deserialize quickly.

4. AMF 3 for ActionScript 3 and AMF 0 is for (AS1 & AS2).

5. AMF 3 supports sending int and uint objects.

6. AMFPHP automatically converts ActionScript data types to PHP data types.

Lets have an example amfPhp and Flex 4.5 connection and data exchange between them.
Step 1 : Install AmfPhp in your wamp server :

amfphp_in_root_directory_www

Step 2 : If installed properly check the gateway.php . It should look like this :

amfphp_gateway_look

Step 3 : Check the browser . It should look like this :

amfphp_in_browser_look

Step 4 : Write a class for php. Here I am writting a dummy data as return which is containing Employee detail.

[xml]

fname = “Aava”;

$emp->lname = “Anjan”;

$emp->age = 28;

return $emp;

}

}

?>

[/xml]

One more class is refrencing the employee. Further we will expand it in our next example .

[xml]

[/xml]
Step 4 : Check the browser and Click on ‘call’ button you will get result like this :

result_on_call

Step 5 : Now Create a new Flex Project where we will see the employee detail by connecting
with AmfPhp . Here are the codes :

[xml]

<?xml version=”1.0″ encoding=”utf-8″?>
<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx” minWidth=”955″ minHeight=”600″>
<fx:Declarations>
<!– Place non-visual elements (e.g., services, value objects) here –>
</fx:Declarations>
<fx:Script>
<![CDATA[
import com.RemotingServiceManager;
import flash.events.MouseEvent;
private var _rc:RemotingServiceManager = new RemotingServiceManager()
protected function search_btn_clickHandler(event:MouseEvent):void{
_rc.getEmployeeDetail();
}
]]>
</fx:Script>
<s:Button id=”search_btn” x=”158″ y=”141″ width=”189″ height=”34″ label=”Click to Get Employee Detail”
click=”search_btn_clickHandler(event)”/>
<s:Label x=”150″ y=”95″ color=”#570404″ fontSize=”17″ text=”Example of Flex and AmfPhp”/>
</s:Application>

[/xml]

Step 6 : Run and Click on the Search button . It will show you result :

flex_result

Tags: , , , , , , , , , , , , , , ,

Flex XML socket connections

November 15th, 2011 by aabhaanjan

Binary Socket Server flex and Java

Before the example I would like give you a brief about XML connections :

XML socket connections vs binary socket connections:
1. An XMLsocket lets create a server connection that remains open until explicitly closed.
2. No need to having to continually open new server connections.
3. No need to explicitly request for sending  data.
The protocol used by the XMLSocket class are :
* XML messages are sent over a full-duplex TCP/IP stream socket connection.
* Each XML message is a complete XML document, terminated by a zero (0) byte.
* An unlimited number of XML messages can be sent and received over a single XMLSocket connection.
XMLSocket has no HTTP tunneling capability.

XML socket connections vs binary socket connections:

1. An XMLsocket lets create a server connection that remains open until explicitly closed.

2. No need to having to continually open new server connections.

3. No need to explicitly request for sending  data.

The protocol used by the XMLSocket class are :

* XML messages are sent over a full-duplex TCP/IP stream socket connection.

* Each XML message is a complete XML document, terminated by a zero (0) byte.

* An unlimited number of XML messages can be sent and received over a single XMLSocket connection.

Note : XMLSocket has no HTTP tunneling capability.
[xml]
<?xml version=”1.0″ encoding=”utf-8″?>
<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:s=”library://ns.adobe.com/flex/spark”
xmlns:mx=”library://ns.adobe.com/flex/mx”
>
<fx:Script>
<![CDATA[

import com.*;
import mx.controls.Alert;
private var _xmlSocket:XMLSocketClient

private function connectToServer(event:MouseEvent):void {
try{
trace(‘Client is trying to connect with server’)
_xmlSocket = new XMLSocketClient()
}
catch(err:Error){
Alert.show(‘error’+err.name);
}
}
private function sendData():void
{
_xmlSocket.send(msg_txt.text);
}
private function onDisconnectClicked():void
{
_xmlSocket.disconnect();
}

]]>
</fx:Script>

<s:Button x=”327″ y=”40″ label=”Disconnect” width=”95″ id=”disconnect_btn” click=”onDisconnectClicked()”/>

<s:Button x=”213″ y=”126″ label=”Send” width=”95″ id=”send_btn” click=”sendData()”/>

<s:TextInput x=”124″ y=”96″ width=”298″ id=”msg_txt” maxChars=”100″/>

<s:Button x=”183″ y=”74″ width=”125″ height=”41″ label=”Connect” click=”connectToServer(event)”/>

</s:Application>
[/xml]

Tags: , , , , , , , , , ,

Flex and Java Server using Binary Socket Connection

November 15th, 2011 by aabhaanjan

Binary Socket Server flex and Java

Binary socket connections

This is an example of Socket Server program in Flex 4.5 for web view.

Basically here Client will be in Flex and Server will be in Java.

[xml]

<?xml version=”1.0″ encoding=”utf-8″?>

<s:Application xmlns:fx=”http://ns.adobe.com/mxml/2009″

xmlns:s=”library://ns.adobe.com/flex/spark”

xmlns:mx=”library://ns.adobe.com/flex/mx”

>

<fx:Script>

<![CDATA[

import mx.controls.Alert;

private var _socket:Socket;

private var _server:String = “localhost”

private var _port:int = 60000

private function connectToServer(event:MouseEvent):void {

try{

trace(‘Client is trying to connect with server’)

_socket=new Socket();

_socket.addEventListener(Event.CONNECT, onConnection);

_socket.addEventListener(ErrorEvent.ERROR, errorHandler);

_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecurityError);

_socket.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);

_socket.connect(_server, _port);

}

catch(err:Error){

Alert.show(‘Cleint is unable to connect’+err.name);

}

}

private function onConnection(e:Event):void {

Alert.show(“Connected to server”);

_socket.addEventListener(ProgressEvent.SOCKET_DATA, onSocketData);

_socket.addEventListener(Event.CLOSE, onDisconnected);

}

private function ioErrorHandler(e:IOErrorEvent):void {

Alert.show(“IO Error: “+e);

}

private function onSecurityError(e:SecurityErrorEvent):void {

Alert.show(“Security Error: “+e);

}

private function errorHandler(e:ErrorEvent):void {

Alert.show(“IO ErrorHandler: “+e);

}

private function onDisconnected(e:Event):void {

Alert.show(“Server Socket is Closed”);

}

private function onSocketData(event:ProgressEvent):void {

var _str:String=””;

while (_socket.bytesAvailable) {

_str+=_socket.readUTFBytes(_socket.bytesAvailable);

}

Alert.show(_str);

}

private function sendToServer(e:MouseEvent):void {

_socket.writeUTFBytes(tField.text + “\r\n”);

_socket.flush();

}

protected function logout(e:Event):void {

if (_socket && _socket.connected) {

_socket.writeUTFBytes(“logout\r\n”);

_socket.flush();

_socket.close();

}

}

]]>

</fx:Script>

<s:TextArea id=”tField” width=”315″ height=”81″ y=”184″ x=”187″/>

<s:Button x=”183″ y=”74″ width=”125″ height=”41″ label=”Connect” click=”connectToServer(event)”/>

<s:Button x=”308″ y=”274″ width=”79″ height=”34″ label=”Send” click=”sendToServer(event)”/>

<s:Button x=”386″ y=”74″ width=”129″ height=”46″ label=”Logout” click=”logout(event)”/>

<s:Label x=”192″ y=”164″ color=”#610404″ text=”Type Your Message for Server”/>

<s:Label x=”241″ y=”35″ width=”300″ color=”#004F99″ fontSize=”15″ text=”Client Side For Socket Server”/>

</s:Application>

[/xml]

Java server :

SocketServer : This Class will initialize crossdomin policy file for the Flash Player.

[xml]

package com.servernew;

public class SocketServer {

public static void main(String[] args) {

SocketServer CrossDomainPolicyServer = new SocketServer(843);

CrossDomainPolicyServer.addListener(new CrossDomainPolicy());

new Thread(CrossDomainPolicyServer).start();

SocketServer MyETFlashBridgeSocketServer = new SimpleSocketServer(6000);

new Thread(MyETFlashBridgeSocketServer).start();

}

}

[/xml]

CrossDomainPolicy :

This is the class to handle Cross-domain-policy request:

[xml]

package com.servernew;

public class CrossDomainPolicy implements SocketServerListener{

public String Communication(String clientData) {

// TODO Auto-generated method stub

String varReturn = “”;

if (clientData.indexOf(“<policy-file-request/>”) > -1){

varReturn= “<cross-domain-policy><allow-access-from domain =\”*\” to-ports =\”*\”/></cross-domain-policy>”;

}

return varReturn;

}

}

[/xml]

SimpleSocketServer :

This is the socket server class which will perform as the server for

flex client.

[xml]

package com.servernew;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Collection;

import java.util.HashSet;

import java.util.Iterator;

public class SimpleSocketServer implements Runnable{

public void Log(String Level, String message){

if (Level != “Trace”){

System.out.println(“[” + Level + “]” + message);

}

}

private int _HostPort = 60000;

private char _SplitChar = ‘\0’;

private char[] _ReadBuffer = new char[32];

private boolean _IsRunable = true;

private Collection<SocketServerListener> Listeners;

private ServerSocket _ServerSocket;

public SimpleSocketServer(int hostPort){

_HostPort = hostPort;

}

public void addListener(SocketServerListener SocketServerListener){

if (Listeners == null){

Listeners = new HashSet<SocketServerListener>();

}

Listeners.add(SocketServerListener);

}

public void removeListener(SocketServerListener SocketServerListener){

if (Listeners == null){

return;

}

Listeners.remove(SocketServerListener);

}

private String SocketCommunication(String clientData){

String varReturn = “”;

if (Listeners != null){

Iterator<SocketServerListener> iter = Listeners.iterator();

while (iter.hasNext()) {

SocketServerListener listener = (SocketServerListener)iter.next();

varReturn += listener.Communication(clientData);

}

}

return varReturn;

}

public void run() {

Log(“Info”, “SocketServer Start at 0.0.0.0:” + this._HostPort);

try {

_ServerSocket = new ServerSocket(this._HostPort);

Log(“Info”, “Listens for a connection…”);

Socket client = _ServerSocket.accept();

Log(“Info”, client.getInetAddress().getHostAddress() + “:” + client.getPort() + “connected”);

BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

Log(“Info”, “BufferedReader getInputStream.”);

PrintWriter out = new PrintWriter(client.getOutputStream());

Log(“Info”, “PrintWriter getOutputStream.”);

int LoopTimes = 0;

while (_IsRunable){

Log(“Info”, “SocketCommunication LoopTimes: ” + (++LoopTimes));

String inString = “”;

int inBufferLength = -1;

while ((inBufferLength = in.read(_ReadBuffer)) != -1 && _IsRunable){

inString += new String(_ReadBuffer);

Log(“Trace”, “inBufferLength,inString.length,IsRunable = [” + inBufferLength + “,” + inString.length() + “,” + _IsRunable + “]”);

if (_ReadBuffer[inBufferLength-1]==_SplitChar){

break;

}

}

Log(“Info”, “ReadBuffer (” + inString.length() + “): ” + inString);

String outString = “”;

if (_IsRunable){

outString = this.SocketCommunication(inString);

}

Log(“Info”, “SocketCommunication Finish.”);

if (_IsRunable){

out.println(outString + _SplitChar);

Log(“Info”, “PrintWriter (” + outString.length() + “): ” + outString);

out.flush();

}

try {

Thread.sleep(1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

while (true){

outString = this.SocketCommunication(“<FlashGame Action=\”STARTRECORD\”>”);

if (outString.length() >0){

out.println(outString + _SplitChar);

Log(“Info”, “PrintWriter (” + outString.length() + “): ” + outString);

out.flush();

}

try {

Thread.sleep(500);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

} catch (IOException e) {

Log(“IOException”, e.getMessage());

}

}

}

[/xml]

SocketServerListener :

[xml]

package com.servernew;

import java.util.EventListener;

public interface SocketServerListener extends EventListener{

public String Communication(String clientData);

}

[/xml]

Tags: , , , , , ,

Calling JavaScript function using navigateToURL

November 15th, 2011 by aabhaanjan

JavaScript and NavigateToURL

In this example we are going to explain
1. How to call a javaScript function.
2. How to pass parameters.
[xml]

xmlns:mx=”library://ns.adobe.com/flex/mx”
xmlns:s=”library://ns.adobe.com/flex/spark”>
click=”callJavaScript(event)”/>

[/xml]

Tags: , , , ,

navigateToURLExample

November 15th, 2011 by aabhaanjan
In this example we will see following points :
1. Sending variable in a form of String using navigateToURL.
2. Opening options for new window

Google Search with navigateToURL

In this example we will see following points :

1. Sending variable in a form of String using navigateToURL.

2. Opening options for new window.

In this example we will open a Google search window using  _self or _blank window. There are other _parent window option is

also which we will see in our other example :

[xml]

<?xml version=”1.0″ encoding=”utf-8″?>

<s:Application

xmlns:fx=”http://ns.adobe.com/mxml/2009″

xmlns:mx=”library://ns.adobe.com/flex/mx”

xmlns:s=”library://ns.adobe.com/flex/spark”>

<fx:Script>

<![CDATA[

import flash.net.*;

import mx.controls.Alert;

import mx.events.CloseEvent;

public function checkWindowOpenMode(event:MouseEvent):void {

Alert.show(“Open new tab to search in Google Maps or self ?”, “”, Alert.YES |Alert.NO, null, alertListener, null, Alert.NO);

}

private function alertListener(eventObj:CloseEvent):void {

var url:String = “http://maps.google.com.au/maps?q=” + search_input.text;

var urlReq:URLRequest = new URLRequest(url);

if (eventObj.detail==Alert.YES){

navigateToURL(urlReq, “_blank”);

}

else if (eventObj.detail==Alert.NO){

navigateToURL(urlReq, “_self”);

}

}

]]>

</fx:Script>

<s:Button x=”325″ y=”170″ width=”94″ height=”35″ label=”Search”

click=”checkWindowOpenMode(event)”/>

<s:TextArea id=”search_input” x=”232″ y=”120″ width=”294″ height=”37″/>

<s:Label x=”225″ y=”78″ color=”#700505″ fontSize=”16″ fontWeight=”bold”

text=”Type your search here for Google map “/>

</s:Application>

[/xml]

Tags: , , , , , ,

How to transfer Array within an Object to JavaScript using External Interface ?

November 4th, 2011 by aabhaanjan
Here is an example :
Flex Side :
<?xml version=”1.0″ encoding=”utf-8″?>
<s:Application
xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:mx=”library://ns.adobe.com/flex/mx”
xmlns:s=”library://ns.adobe.com/flex/spark”>
<s:layout>
<s:HorizontalLayout/>
</s:layout>
<fx:Script><![CDATA[
import flash.external.*;
public function callJavaScriptFunction():void {
var msg:String;
if (ExternalInterface.available) {
var _obj:Object = new Object();
_obj.fname = “Aava”;
_obj.lname = “Rani”;
_obj.familly = new Array(‘RP’,’AK’,’SK’,’BK’);
msg = ExternalInterface.call(‘receiveComplexDataTypes’, _obj);
} else {
msg = “Not available”;
}
}
]]></fx:Script>
<s:Button label=”Send Data” click=”callJavaScriptFunction()”/>
</s:Application>
HTML Side :-
<!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” lang=”en” xml:lang=”en”>
<head>
<title>Complex Data and ExternalInterface Example</title>
<script type=”text/javascript” src=”swfobject.js”></script>
<script type=”text/javascript”>
var swfVersionStr = “0”;
var xiSwfUrlStr = “”;
var flashvars = {};
var params = {};
params.quality = “high”;
params.bgcolor = “#ffffff”;
params.allowscriptaccess = “sameDomain”;
var attributes = {};
attributes.id = “ComplexDataExternalInterface”;
attributes.name = “ComplexDataExternalInterface”;
attributes.align = “middle”;
swfobject.embedSWF(
“ComplexDataExternalInterface.swf”, “flashContent”,
“100%”, “100%”,
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
</script>
</head>
<SCRIPT LANGUAGE=”JavaScript”>
function receiveComplexDataTypes(object) {
var str = (“The Data values are :- ” + object.fname + ” \n and :-” + object.lname + “!”);
for (i=0; i<object.familly.length; i++) {
str +=  i + “: ” + object.familly [i] + “\n”;
}
alert(str);
return “successful”;
}
</SCRIPT>
<body>
<div id=”flashContent”/>
</body>

Here is an example :

Flex Side :

[xml]

<?xml version=”1.0″ encoding=”utf-8″?>

<s:Application

xmlns:fx=”http://ns.adobe.com/mxml/2009″

xmlns:mx=”library://ns.adobe.com/flex/mx”

xmlns:s=”library://ns.adobe.com/flex/spark”>

<s:layout>

<s:HorizontalLayout/>

</s:layout>

<fx:Script><![CDATA[

import flash.external.*;

public function callJavaScriptFunction():void {

var msg:String;

if (ExternalInterface.available) {

var _obj:Object = new Object();

_obj.fname = “Aava”;

_obj.lname = “Rani”;

_obj.familly = new Array(‘RP’,’AK’,’SK’,’BK’);

msg = ExternalInterface.call(‘receiveComplexDataTypes’, _obj);

} else {

msg = “Not available”;

}

}

]]></fx:Script>

<s:Button label=”Send Data” click=”callJavaScriptFunction()”/>

</s:Application>

[/xml]

HTML Side :-

[xml]

<!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” lang=”en” xml:lang=”en”>

<head>

<title>Complex Data and ExternalInterface Example</title>

<script type=”text/javascript” src=”swfobject.js”></script>

<script type=”text/javascript”>

var swfVersionStr = “0”;

var xiSwfUrlStr = “”;

var flashvars = {};

var params = {};

params.quality = “high”;

params.bgcolor = “#ffffff”;

params.allowscriptaccess = “sameDomain”;

var attributes = {};

attributes.id = “ComplexDataExternalInterface”;

attributes.name = “ComplexDataExternalInterface”;

attributes.align = “middle”;

swfobject.embedSWF(

“ComplexDataExternalInterface.swf”, “flashContent”,

“100%”, “100%”,

swfVersionStr, xiSwfUrlStr,

flashvars, params, attributes);

</script>

</head>

<SCRIPT LANGUAGE=”JavaScript”>

function receiveComplexDataTypes(object) {

var str = (“The Data values are :- ” + object.fname + ” \n and :-” + object.lname + “!”);

for (i=0; i<object.familly.length; i++) {

str +=  i + “: ” + object.familly [i] + “\n”;

}

alert(str);

return “successful”;

}

</SCRIPT>

<body>

<div id=”flashContent”/>

</body>

[/xml]

Tags: , , , , , , , ,

How to transfer complex data to JavaScript using External Interface ?

November 4th, 2011 by aabhaanjan

Here is an example :
Flex Side :
[java]
<?xml version=”1.0″ encoding=”utf-8″?>
<s:Application
xmlns:fx=”http://ns.adobe.com/mxml/2009″
xmlns:mx=”library://ns.adobe.com/flex/mx”
xmlns:s=”library://ns.adobe.com/flex/spark”>
<s:layout>
<s:HorizontalLayout/>
</s:layout>
<fx:Script><![CDATA[
import flash.external.*;

public function callJavaScriptFunction():void {
var msg:String;
if (ExternalInterface.available) {
var _obj:Object = new Object();
_obj.fname = “Aava”;
_obj.lname = “Rani”;
msg = ExternalInterface.call(‘receiveComplexDataTypes’, _obj);
} else {
msg = “Not available”;
}
}
]]></fx:Script>

<s:Button label=”Send Data” click=”callJavaScriptFunction()”/>

</s:Application>
[/java]
HTML Side :-
[xml]
<!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” lang=”en” xml:lang=”en”>
<head>
<title>Complex Data and ExternalInterface Example</title>
<script type=”text/javascript” src=”swfobject.js”></script>
<script type=”text/javascript”>
var swfVersionStr = “0”;
var xiSwfUrlStr = “”;
var flashvars = {};
var params = {};
params.quality = “high”;
params.bgcolor = “#ffffff”;
params.allowscriptaccess = “sameDomain”;
var attributes = {};
attributes.id = “ComplexDataExternalInterface”;
attributes.name = “ComplexDataExternalInterface”;
attributes.align = “middle”;
swfobject.embedSWF(
“ComplexDataExternalInterface.swf”, “flashContent”,
“100%”, “100%”,
swfVersionStr, xiSwfUrlStr,
flashvars, params, attributes);
</script>
</head>

<SCRIPT LANGUAGE=”JavaScript”>
function receiveComplexDataTypes(object) {
alert(“The Data values are :- ” + object.fname + ” \n and :-” + object.lname + “!”);
return “successful”;
}
</SCRIPT>

<body>
<div id=”flashContent”/>
</body>
</html>
[/xml]

Tags: , , , , , , , , , ,