Posts Tagged ‘connection’

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: , , , , , ,

Smartfox Server-Chapter 02-Connection with Server

October 1st, 2010 by aabhaanjan

Establish connection with server

To make connection between server and client we need three most important parts :

IP : IP of system where smartfox is Installed.

Port : Port number by default it is 9339.

Zone : name of zone where you want to make the connection.

At first I would like to suggest you to make a config.xml file which will have above three essential parts in the form of their node. Now the first question will come in your mind why XML when we can declare it inside the action script code ? So answer is it will make your life easy. During the various stages of development you will need to change the IP at that time it will be easy to modify it from outside. Therefore here I have used the same way and created this config.xml.

1

Now what we need to do with Action script to establish the connection? Create a screen with a dynamic text box where we will show the status of connection.

2

Now create a document class : Paste following codes :

34

In above code we are importing the packages of smartfox then we are calling two smartfox event “onConnectToSFS” and “onConnectionLost” which will show the status of connection. Now by using “LoadConfigData” function we are loading the config.xml. On config loaded we are getting the IP,Port and zone by using this we are calling the function connectToSfs where we are sending request for connection to the server. If connection will succeed the text box will show the message “Connected”. On connection loss the text box will show the message “Disconnected”.

5

Now lets move to the next chapter where we will discuss detail about the config structure . We will discuss what is the meaning of other nodes of above structure.

Previous Chapter :                                                                                                                                                                                            Next Chapter :

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