https://simplapi.wordpress.com/2012/07/02/linking-socket-io-to-qooxdoo/


Qooxdoo is a great framework, but sometimes you need to add extra content to it, and this is not so simple.

Here is a basic class and idea to link Socket.IO client API to Qooxdoo framework :

Before playing

Before doing anything with Socket.IO, you first need to include thooses files into your project.
Start getting Node.JS, and installing Socket.IO using « npm install socket.io ». This should install in node_module (in node.js root folder) socket.io folder. Inside this node_module, you should find the client API of Socket.IO here :
%NODE_ROOT%/node_modules/socket.io/node_modules/socket.io-client/dist

The dist folder should contains 4 files :

  • socket.io.js
  • socket.io.min.js
  • WebSocketMain.swf
  • WebSocketMainInsecure.swf

Regarding what you want, you need only 3 files : choose between the socket.io.js and the min version. I will prefer here the minimal but it does not change so much things after all.

I didn’t find the good way to put thooses files in the qooxdoo main project, but this should do the trick :
On resource folder, create a script folder, create inside this folder a « socket » (what you want for this one) folder. Put 3 files into this one.

Now you have the socket.io resource folder on your Qooxdoo app. But it’s not enough for now.

On the config.json file, you need to force the system to copy it, I use here the « build-script » which is the remapped default build folder :

1
2
3
4
5
6
7
8
9
10
11
12
13
"jobs":{
    "build-script":{
        "copy-files" :{
            "files":[
                "./script/socket/"
            ],
            "source" : "./source/resource/",
            "target"  : "./build/"
        },
        "add-script":[{
            "uri":"script/socket/socketio.js"
        }]
(...)

The add-script is the most important part, it force the system to load the script as part of the qooxdoo launch. The script will be launched around Application.main start (I didn’t check exactly but before it’s too early and at the end of main it’s available).

Now you can play with Socket.IO over Qooxdoo, here is a basic class to deal with inside Qooxdoo system (under LGPLv3, like all sources I post here) :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/**
 * This class is a direct link with socket.io.
 */
qx.Class.define("myapp.api.WebSocket",{
    extend : qx.core.Object,
 
    //Socket.io events
    events :{
        /** socket.io connect event */
        "connect"           : "qx.event.type.Event",
        /** socket.io connecting event */
        "connecting"        : "qx.event.type.Data",
        /** socket.io connect_failed event */
        "connect_failed"    : "qx.event.type.Event",
        /** socket.io message event */
        "message"           : "qx.event.type.Data",
        /** socket.io close event */
        "close"             : "qx.event.type.Data",
        /** socket.io disconnect event */
        "disconnect"        : "qx.event.type.Event",
        /** socket.io reconnect event */
        "reconnect"         : "qx.event.type.Data",
        /** socket.io reconnecting event */
        "reconnecting"      : "qx.event.type.Data",
        /** socket.io reconnect_failed event */
        "reconnect_failed"  : "qx.event.type.Event",
        /** socket.io error event */
        "error"             : "qx.event.type.Data"
    },
 
    properties:{
        /**
         * The url used to connect to socket.io
         */
        url:{
            nullable:   false,
            init:       "http://"+window.location.hostname+"/",
            check:      "String"
        },
        /** The port used to connect */
        port:{
            nullable:   false,
            init:       8080,
            check:      "Number"
        },
        /** The namespace (socket.io namespace), can be empty */
        namespace:{
            nullable:   true,
            init:       "",
            check:      "String"
        },
        /** The socket (socket.io), can be null */
        socket:{
            nullable:   true,
            init:       null,
            check:      "Object"
        },
        /** Parameter for socket.io indicating if we should reconnect or not */
        reconnect:{
            nullable:   true,
            init:       true,
            check:      "Boolean"
        },
        connectTimeout:{
            nullable:   true,
            init:       10000,
            check:      "Number"
        },
        /** Reconnection delay for socket.io. */
        reconnectionDelay:{
            nullable:   false,
            init:       500,
            check:      "Number"
        },
        /** Max reconnection attemps */
        maxReconnectionAttemps:{
            nullable:   false,
            init:       1000,
            check:      "Number"
        }
    },
 
    /** Constructor
     *
     * @param namespace {string ? null} The namespace to connect on
    */
    construct: function(namespace){
        this.base(arguments);
        if(namespace !== null){
            this.setNamespace(namespace);
        }
        this.__name = [];
    },
 
    members:{
        //The name store an array of events
        __name : null,
 
        /**
         * Trying to using socket.io to connect and plug every event from socket.io to qooxdoo one
        */
        connect:function(){
            if(this.getSocket() != null){
                this.getSocket().removeAllListeners();
                this.getSocket().disconnect();
            }
            this.setSocket(io.connect(this.getUrl()+this.getNamespace(), {
                'port': this.getPort(),
                'reconnect': this.getReconnect(),
                'connect timeout' : this.getConnectTimeout(),
                'reconnection delay': this.getReconnectionDelay(),
                'max reconnection attempts': this.getMaxReconnectionAttemps(),
                'force new connection':true
            }));
 
            this.on("connect",          function(){     this.fireEvent("connect");                  }, this);
            this.on("connecting",       function(e){    this.fireDataEvent("connecting", e);        }, this);
            this.on("connect_failed",   function(){     this.fireEvent("connect_failed");           }, this);
            this.on("message",          function(e){    this.fireDataEvent("message", e);           }, this);
            this.on("close",            function(e){    this.fireDataEvent("close", e);             }, this);
            this.on("disconnect",       function(){     this.fireEvent("disconnect");               }, this);
            this.on("reconnect",        function(e){    this.fireDataEvent("reconnect", e);         }, this);
            this.on("reconnecting",     function(e){    this.fireDataEvent("reconnecting", e);      }, this);
            this.on("reconnect_failed", function(){     this.fireEvent("reconnect_failed");         }, this);
            this.on("error",            function(e){    this.fireDataEvent("error", e);             }, this);
        },
 
        /**
         * Emit an event using socket.io
         *
         * @param name {string} The event name to send to Node.JS
         * @param jsonObject {object} The JSON object to send to socket.io as parameters
        */
        emit:function(name, jsonObject){
            this.getSocket().emit(name, jsonObject);
        },
 
        /**
         * Connect and event from socket.io like qooxdoo event
         *
         * @param name {string} The event name to watch
         * @param fn {function} The function wich will catch event response
         * @param that {mixed} A link to this
        */
        on:function(name, fn, that){
            this.__name.push(name);
            if(typeof(that) !== "undefined" && that !== null){
                this.getSocket().on(name, qx.lang.Function.bind(fn, that));
            }else{
                this.getSocket().on(name, fn);
            }
        }
    },
 
    /**
     * Destructor
     */
    destruct : function(){
        if(this.getSocket() != null){
            //Deleting listeners
            if(this.__name !== null && this.__name.length >= 1){
                for(var i=0; i<this.__name.length; ++i){
                    this.getSocket().removeAllListeners(this.__name[i]);
                }
            }
            this.__name = null;
 
            this.removeAllBindings();
 
            //Disconnecting socket.io
            try {
                this.getSocket().socket.disconnect();
            } catch(e) {}
 
            try {
                this.getSocket().disconnect();
            } catch(e) {}
 
            this.getSocket().removeAllListeners("connect");
            this.getSocket().removeAllListeners("connecting");
            this.getSocket().removeAllListeners("connect_failed");
            this.getSocket().removeAllListeners("message");
            this.getSocket().removeAllListeners("close");
            this.getSocket().removeAllListeners("disconnect");
            this.getSocket().removeAllListeners("reconnect");
            this.getSocket().removeAllListeners("reconnecting");
            this.getSocket().removeAllListeners("reconnect_failed");
            this.getSocket().removeAllListeners("error");
        }
    }
});

This class can be used like this :

1
2
3
4
5
6
7
8
9
10
var ws = new myapp.api.WebSocket();
//Here you should customize port, hostname, ...
 
//Connect with previous setted properties
ws.connect();
 
ws.emit("achannel", "hello");
ws.on("achannel", function(result){
  console.log(result);
}, this);

Simple as this !

closure란 내부함수가 외부함수의 Context에 접근할 수 있는 것이다


즉 클레스의 멤버처럼 쓸수 있는 것인데, 말로써 설명은 잘 못하겠고 예제를 참조하자.


예제 1)

(function() {
var nData = 10;

var testFunction = function() {
console.log(nData); // nData값을 참조한다.
};

testFunction(); // console에 10이 찍힌다.
})();


예제처럼 testFunction 안에서 nData를 참조했고 console 출력을 했다.


여기서 주의 점이 하나 있는데 함수 실행시점 값을 참조한다는 것이다.


또 말보단 예제로 .


예제2)


(function() {

var nData = 10;


var testFunction = function() {
console.log(nData); // nData값을 참조한다.
};

// 여기까진 nData가 10
testFunction(); // console에 100 이 찍힌다.

nData = 100;
// 여기서부터 nData가 100
testFunction(); // console에 100 이 찍힌다.

})();


주의

예제 2)같이 10을 원했는데 100이 나오는 실수가 많이 발생한다고 한다.

xcode Download 한다.

실행후 Command Line Tools 설치 후 종료.

 

http://brew.sh/

brew 설치.

터미널에서 -> ruby -e "$(curl -fsSL https://raw.github.com/mxcl/homebrew/go)"

터미널 재실행.

 

npm 설치

터미널에서 -> brew install npm

localhost:Documents Wind$ brew install npm

터미널 재실행.

 

// xcode를 미설치나 미동의시 아래같은 내용이 나올 수 있다.

Warning: You have not agreed to the Xcode license.

Builds will fail! Agree to the license by opening Xcode.app or running:

    xcodebuild -license

 

nvm 설치

  • curl https://raw.github.com/creationix/nvm/master/install.sh | sh
  • open a new terminal window (or do a shell logout + login)
  • touch /User/userid/.profile 라고 친후 재인스톨.
  • nvm install 0.8
  • nvm use 0.8
  • node --version 으로 0.8.x 버전인지 확인. (컴파일은 0.8 버전대밖에 되지 않는다.)
npm install -g sm
git clone https://github.com/ajaxorg/cloud9.git

 

Tomcat 7.x 에서는 기본적으로 압축이 지원된다고 한다.


환경설정만 바꿔주면 된다.


1. /Tomcat/conf 이동후 server.xml 파일 오픈한다.

2. 내용검색으로 port="8080" 를 검색한다.

3. 아래 내용을 입력한다.

compression="on"

compressionMinSize="2048"

noCompressionUserAgents="gozilla, traviata"

compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css,application/javascript"


즉 아래처럼 보일것이다.

<Connector port="8080" protocol="HTTP/1.1"

               connectionTimeout="20000"

               redirectPort="8443" 

               compression="on"

               compressionMinSize="2048"

               noCompressionUserAgents="gozilla, traviata"    compressableMimeType="text/plain,text/html,text/xml,application/xhtml+xml,application/xml,application/rss+xml,text/css,application/javascript,application/x-javascript,audio/midi"/>

               compressableMimeType="text/plain,text/html,text/xml,application/xhtml+xml,application/xml,application/rss+xml,text/css,application/javascript,application/x-javascript,audio/midi"/>


Connector 노드에 

compression, compressionMinSize, noCompressionUserAgents, compressableMimeType 노드를 추가합니다.


compression : default "off" 

압축전송기능 사용여부를 설정합니다. 당연히 이 기능을 쓰기위해선 on으로 설정해야합니다.


compressionMinSize : default "2048"

byte단위로 몇 이상 크기부터 압축할지를 결정합니다.

너무 작은 크기를 압축하면 오히려 서버의 자원낭비가 될 수 있습니다.

(물론 작은크기에서 압출률도 별로 의미가 없습니다.)


noCompressionUserAgents : default ""

압축을 사용하지 않을 유저에이전트(브라우저)를 설정합니다.


compressableMimeType : default ""

압축을 사용할 파일분류를 설정합니다.


추가로 IE 7(?) 포함한 이하버전과 넷스케이프 4(?)포함 이하버전은 gzip 전송하면 안된다.

noCompressionUserAgents 를 변경해야될지 몰르겠다.


// 옵션에 상세 설명은 여기가서 확인하면 된다.

http://tomcat.apache.org/tomcat-7.0-doc/config/http.html


※ 추가 

ehcache lib를 이용한 zip 압축하기


http://pupustory.tistory.com/257




이번에도 맥기준으로 나열한다. (톰켓아닌 맥 기본 apache 설정이다.)


deflate_module 를 이용한 gzip 압축


환경설정만 바꿔주면 된다.


1. /private/etc/apache2 폴더로 이동한다.

2. 텍스트에디터서 httpd.conf 를 연다.

3. 이라인이 있는지 확인한다. "LoadModule deflate_module libexec/apache2/mod_deflate.so"

4. 아래의 내용을 적당한곳에 추가한 후 서버를 재시작 한다.

<IfModule deflate_module>

  # 압축 할 파일 설정

  AddOutputFilterByType DEFLATE text/plain text/html text/xml

  AddOutputFilterByType DEFLATE application/xhtml+xml application/xml application/rss+xml

  AddOutputFilterByType DEFLATE text/css application/javascript application/x-javascript

  AddOutputFilterByType DEFLATE audio/midi


  # DeflateCompressionLevel는 사용할 압축수준을 선택한다. 값이 클수록 압축률이 증가하지만, CPU를 더 많이 사용한다.

  DeflateCompressionLevel 9 # 압축 레벨 1 ~ 9 까지 존재.

  DeflateBufferSize 2048


  BrowserMatch ^Mozilla/4 gzip-only-text/html   # Netscape 4.xx에는 HTML만 압축해서 보냄

  BrowserMatch ^Mozilla/4\.0[678] no-gzip   # Netscape 4.06~4.08에는 압축해서 보내지 않음

  BrowserMatch \bMSIE !no-gzip !gzip-only-text/html   # 자신을 Mozilla로 알리는 MSIE에는 그대로 압축해서 보냄

</ifModule>


5. 추가 치시어는 deflate_module 에서 확인 하면된다.



'Dev > Apache' 카테고리의 다른 글

Apache Tomcat gzip 압축전송하기.  (0) 2013.09.13
맥에서 웹 공유(Apache)기능 활성화 하기.  (0) 2013.09.13
맥에 Tomcat 설치하기. (Ver.7.x)  (0) 2013.09.09

웹공유 활성화 하기. use Terminal


켜기 : sudo apachectl start

끄기 : sudo apachectl stop

재시작 : sudo apachectl restart



웹공유를 터미널리 아닌 GUI 방식으로 켜고 끄고 싶다면 


http://macnews.tistory.com/150 를 참고 하여 변경한다.



Coda2 를 이용하여 켜고 끄는 방법도 있다.


http://www.panic.com/coda/plugins.php 에 접속하여 플러그 인을 다운받는다.



Web Sharing 를 다운받아 압축을 풀고 클릭만 해주면

Coda2 메뉴 - plug-ins 부분에 등록된다.


단축키 : control + option + command + W


사용법은 간단하다. 실행해보면 아래와 같은 팝업이 생성되며 클릭만으로 켜고 끌수 있다.


- 준비하기

1. python : http://www.python.org/download/

2. PIL : http://www.pythonware.com/products/pil/ 에서 PIL 을 다운로드.

3. pypacker : http://jwezorek.com/2013/01/sprite-packing-in-python/


- 설치하기

1. python 설치는 mac 에는 기본 설치므로 넘어간다.

2. PIL 설치

 - 압축을 적당한곳에 푼다.

 - Terminal 을 통해 해당 폴더로 간후 "python setup.py install" 후 끝.


3. pypacker.py 파일은 적당한 위치에 넣는다.


- 사용방법

 "python pypacker.py -i /Download/input -o /Download/output"

하면 png와 plist(xml?) 파일이 생긴다.


 

 

pypack_output.plist



-o 에 폴더 입력하지 않으면 pypacker 있는 폴더에 저장된다.


◎ 사라질것을 대비하여 파일을 첨부한다.

 

Imaging-1.1.7.tar.gz


 

pypacker.zip




톰켓 설치.

1. 톰켓 사이트 접속.


순서대로 1(클릭) -> 2(다운로드) 한다.


적당한곳에 풀어 넣는다.


use Terminal


서버 시작 : tomcat/bin/startup.sh

서버 끄기 : tomcat/bin/shutdown.sh


※ catalina.out: Permission denied 이러면서 실행 안되는 경우가 있다.

터미널에서 "chmod a+x /path/to/tomcat/bin/catalina.sh"

적용해주고 서버 시작하면 된다.


http://www.ibm.com/developerworks/web/library/wa-memleak/


1. 순환참조(leak)

var object = {

key: 1,

value:200,

data:null

}


object.data = object;


2. 순환참조 (1번과 비슷한 경우)(leak)


3. 클로저 안에서 aguments를 어느 변수에 담고 그 안에서 또 참조하는경우(leak)


4. 4번예제처럼 작성을 하라.(정상)

1. 프로젝트 만들기


qooxdoo/tool/bin> python create-application.py 를 하면 아래와 같이 설명이 나온다.

Usage: create-application.py --name APPLICATIONNAME [--out DIRECTORY]
                             [--namespace NAMESPACE] [--type TYPE]
                             [-logfile LOGFILE] [--skeleton-path PATH]

Script to create a new qooxdoo application.

Example: For creating a regular GUI application 'myapp' you could execute:
  create-application.py --name myapp

Options:
  -h, --help            show this help message and exit
  -n APPLICATIONNAME, --name=APPLICATIONNAME
                        Name of the application. An application folder with
                        identical name will be created. (Required)
  -o DIRECTORY, --out=DIRECTORY
                        Output directory for the application folder. (Default:
                        .)
  -s NAMESPACE, --namespace=NAMESPACE
                        Applications's top-level namespace. (Default:
                        APPLICATIONNAME)
  -t TYPE, --type=TYPE  Type of the application to create, one of:
                        ['contribution', 'desktop', 'inline', 'mobile',
                        'native', 'server', 'website'].'contribution' -- is
                        suitable for qooxdoo-contrib; 'desktop' -- is a
                        standard qooxdoo GUI application; 'inline' -- is an
                        inline qooxdoo GUI application; 'mobile' -- is a
                        qooxdoo mobile application with full OO support and
                        mobile GUI classes; 'native' -- is a qooxdoo
                        application with full OO support but no GUI classes;
                        'server' -- for non-browser run times like Rhino,
                        node.js; 'website' -- can be used to build low-level
                        qooxdoo applications. (Default: desktop)
  -l LOGFILE, --logfile=LOGFILE
                        Log file
  -p PATH, --skeleton-path=PATH
                        (Advanced) Path where the script looks for skeletons.
                        The directory must contain sub directories named by
                        the application types. (Default: /Library/WebServer/Do
                        cuments/Quad/qooxdoo-2.0.1-sdk/component/skeleton)
  --cache=PATH          Path to the cache directory; will be entered into
                        config.json's CACHE macro (Default:
                        ${TMPDIR}/qx${QOOXDOO_VERSION}/cache)



데스크탑 웹페이지를 기준으로 프로젝트 생성을 하는 기준으로 설명한다. ( 다른것을 원한다면 type를 변경하면된다.)

applicationName : "testproject",

path:"/Document/projectRoot"

python create-application.py -n testproject -p /Document/projectRoot


라고 입력하면 "/Document/projectRoot/testproject/" 에 파일들이 생성된다.


주의: applicationName 은 소문자로 만드세요


+ Recent posts