wtorek, 7 kwietnia 2009

Simple actionscript logging via socket with python socket server

So you want simple logging to external resources.

ex. live your application working for a long night and then check how it was doing it's job

try something like that:

first we will setup simple socket server - without any extensions only one single connection

#-*- coding: utf-8 -*-

import socket
import sys


hostname = 'localhost'
port = 2000
if len(sys.argv) < 3:
print 'For custom: %s [host name] [port number]' % sys.argv[0]
#sys.exit(1)
else :
hostname = sys.argv[1]
port = int(sys.argv[2])
print 'now is', hostname, port
# makes socket server
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

# add socket to port and listen
sock.bind((hostname, port))
sock.listen(1)
print '--- Logging started ---'

# service of the response
request, clientAddress = sock.accept()
# send some message
request.send('Is logging --- simple python logger --- 0.0.1 alpha')
while 1:
data = request.recv(1024)
if data :
print str(data)
else :
#stop logging
print '--- Logging stopped ---'
sock.close()
break


then we want some simple logging class

package pl.vane.logging
{
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.ProgressEvent;
import flash.events.SecurityErrorEvent;
import flash.net.Socket;

public class ALog
{

private static var socket:Socket

private static var _host:String;
private static var _port:int;

private static var _connected:Boolean = false;

public function ALog()
{

}

//--------------- PUBLIC ------------------

public static function initLogging(host:String = 'localhost', port:int = 2000):void
{
_host = host;
_port = port;

socket = new Socket();

socket.addEventListener(Event.CONNECT, conn);
socket.addEventListener(ProgressEvent.SOCKET_DATA, data);
socket.addEventListener(IOErrorEvent.IO_ERROR, error);
socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, error);

try
{
socket.connect(_host, _port);
}catch(e:Error)
{
trace(e);
}
}

public static function connect():void {
try
{
socket.connect(_host, _port);
}catch(e:Error)
{
trace(e);
}
}

public static function isLogging():Boolean {
return _connected;
}

public static function log(t:ALogType, message:String):void
{
if(socket.connected) {
var s:String = t.type+': '+message;
socket.writeUTFBytes(s);
socket.flush();
} else {
trace('ALog not connected');
}

}

public function toString():String {
return 'pl.vane.logging.ALog'
}

//--------------- PRIVATE ------------------
private static function conn(e:Event):void {
if(socket.connected)
{
_connected = true;
}
}

private static function data(e:ProgressEvent):void
{
if(socket.connected)
{
var s:String = socket.readUTFBytes(socket.bytesAvailable);
trace('LOGGING RESPONSE: ', s);
}
}

private static function error(e:Event):void
{
trace(e);
}

}
}


and I added some usefull headers with types to the message

package pl.vane.logging
{
public class ALogType
{

public static const WARN:ALogType = new ALogType('WARN');
public static const ERROR:ALogType = new ALogType('ERROR');
public static const INFO:ALogType = new ALogType('INFO');
public static const LOG:ALogType = new ALogType('LOG');
public static const DUMP:ALogType = new ALogType('DUMP');

private var _type:String;

public function ALogType(type:String)
{
_type = type;
}

public function get type():String
{
return _type;
}

public function toString():String {
return 'pl.vane.logging.ALogType'
}

}
}


well it won't be perfect but it's working :)
so simple work with AIR application will be something like this




import pl.vane.logging.*;
import flash.utils.clearInterval;
import flash.utils.setInterval;

private var logInterval:uint;

private function complete():void
{
ALog.initLogging();
logInterval = setInterval(initLogging, 1000);
}

private function initLogging():void {
if(ALog.isLogging()) {
// state complete
ALog.log(ALogType.DUMP, 'start of socket logger');
clearInterval(logInterval);
return
} else {
ALog.connect();
trace('not logging');
}
}
]]>





first we initialize the logging interface by calling

ALog.initLogging();

then if it fails we are setting the interval by calling simply

Alog.connect()

via interval function
if it logs the method

ALog.isLogging()

returns true so we can send some message and clear interval

in this example we can try send messages with pressing the button for test :)

happy logging

poniedziałek, 6 kwietnia 2009

1...2...3 syntax highlight

1. Python syntax test - some request code
 
import urllib2
import threading

# Code for continous request http://www.google.pl
print "Get some data"
request = urllib2.Request('http://www.google.pl/')
request.add_header('User-Agent', 'Mozilla')
handler = urllib2.HTTPHandler()
opener = urllib2.build_opener(handler)
data = opener.open(request).read()
thread = threading
# Methods
# make new request in 30 seconds
def runTimer():
timer = None
timer = thread.Timer(30, secondRequest)
timer.start()

# second request
def secondRequest():
seconddata = opener.open(request).read()
data = 'null'
runTimer()
print 'request'

print 'request'
runTimer()



2. MXML Syntax Test - some socket


creationComplete="handleComplete(event)">

import mx.core.UIComponent;
import mx.messaging.channels.NetConnectionChannel;
private var socket:Socket;

private function handleComplete(e:Event):void {
var ui:UIComponent = new UIComponent;
}

private function connect():void {
socket = new Socket();
socket.addEventListener(Event.CONNECT, handleConnect)
socket.addEventListener(ProgressEvent.SOCKET_DATA, handleData);
try {
socket.connect('localhost', 2000);
} catch(e:Error) {
trace(e.toString());
}
}

private function handleData(e:ProgressEvent):void {
if(socket.connected) {
responseText.text+= socket.readUTFBytes(socket.bytesAvailable);
}
socket.close();
}

private function handleConnect(e:Event):void {
responseText.text += 'socket connected\n'
}
]]>







3. ActionScript 3 Syntax Test - some preloader stuff

package pl.vane.preloader.
{
import flash.display.Bitmap;
import flash.display.Sprite;
import flash.events.Event;
import flash.system.Capabilities;

import mx.events.FlexEvent;
import mx.preloaders.DownloadProgressBar;

public class CustomPreloader extends DownloadProgressBar
{

[Embed(source="../../../../../assets/logo.jpg")]
private var LOGO:Class;

private var _startupBMP:Bitmap;

private var p:Sprite;

public function CustomPreloader()
{
super();
_startupBMP = new Bitmap(Bitmap(new LOGO()).bitmapData);
addChild(_startupBMP);
addEventListener(Event.ADDED_TO_STAGE, add);
}

private function add(e:Event):void {
stage.addEventListener(Event.RESIZE, resizeElements);
_startupBMP.x = (Capabilities.screenResolutionX - _startupBMP.width) * .5;
_startupBMP.y = (Capabilities.screenResolutionY - _startupBMP.height) * .5;
}

override public function set preloader(preloader:Sprite):void {
p = preloader;
p.addEventListener(FlexEvent.INIT_COMPLETE, initEnd);
}

// Event listeners for the FlexEvent.INIT_COMPLETE event.
private function initEnd(event:Event):void {
event.preventDefault();
stage.removeEventListener(Event.RESIZE, resizeElements);
p.removeEventListener(FlexEvent.INIT_COMPLETE, initEnd);
cp();
}

private function cp():void {
dispatchEvent(new Event(Event.COMPLETE));
}

private function resizeElements(e:Event):void {
centerElements();
}

private function centerElements():void {
_startupBMP.x = (Capabilities.screenResolutionX - _startupBMP.width) * .5;
_startupBMP.y = (Capabilities.screenResolutionY - _startupBMP.height) * .5;
}

}
}