BLOG main image
분류 전체보기 (117)
Hidden (1)
five senses (0)
safe system (77)
code (35)
database (1)
Link (0)
Visitors up to today!
Today hit, Yesterday hit
daisy rss
tistory 티스토리 가입하기!
'code'에 해당되는 글 35건
2012. 2. 2. 16:12

 

1.
find -iname '*.java' | xargs vim
이런 식으로 편집할 모든 파일을 vim 으로 엽니다.
(파일명/디렉토리명에 공백이 있다면 find -iname '*.java' -print0 | xargs -0 vim)

2.
qq (매크로 시작)
:%s/\v\/\/.*$|\/\*[^\n]*\*\///g | w | n (주석 없애고 다음 파일로 이동)
q (매크로 끝)

3.
파일 갯수만큼 매크로를 호출하기 위하여,
넉넉하게 1000@q 정도로 입력합니다.

2009. 4. 18. 05:00


ㅇ putty 설정값 백업

http://kldp.org/node/42609 에서 인용
regedit을 실행하신 다음에
내 컴퓨터\HKEY_CURRENT_USER\Softeare\Simon Tatham\PuTTY 에 있습니다.

호스트키까지 똥째로 저장하시려면 이 뿌띠 키(디렉토리처럼 생긴거)를 통째로 저장하거나 아니면 이아래에 있는 Session키를 저장하시면 됩니다. (한번 저장해놓고 여러 컴퓨터에서 활용하시려면 Session 만 저장하세요)

왼쪽트리에서 키를 선택하고 나서 메뉴에서 레지스트리->레지스트리 파일 내보내기->선택한 분기 에서 "PuTTYHosts.reg" 처럼 원하시는 이름으로 저장하세요.

이 파일을 더블클릭하시면 설정값들을 다시 입력하실수 있습니다. 자신이 쓰는 깨끗하게 호스트들을 깨끗하게 정리해서 만들어놓고 웹에 올려놓으면, 어디서든지 뿌띠하고 이 파일을만 받아서(뿌띠도 설치할 필요 없으니) 바로 사용할수 있어서 편합니다.


ㅇ putty private key 파일을 openssh 키파일로 변환할려면

http://kldp.org/node/74183 참고
public key는 Putty Key Generator의 상단에 보면 복사할수 있고요,
private key는 메뉴에서 Conversions->"Export OpenSSH key"로 pem 파일로 저장할수 있습니다.

public key는 authorized_keys 파일에 추가하고, id_rsa.pub나 id_dsa.pub 등으로 저장하면 되고,

private key는 id_rsa나 id_dsa로 저장하면 됩니다.

ㅇ openssh 에서 만든 private 키를 putty로 옮기기

키를 윈도우로 가지고와서 프로그램에서 Conversions -> Import key 를 이용하면 된다.
여기서 주의할점. 아래와 같이 KEY 내용이 끝나고 엔터키가 있어야한다.

-----BEGIN RSA PRIVATE KEY-----
MIICWgIBAAKBgQCvxDhf4cFa8vUSLi1EZDSYFyzChwZ41Tfdv92ma/sN8RTQ4rKJ
iK2xQSjvKUIA0RC/ieWy70PfPvSNtsJIXw2xyGJ1YtvvY4Gjy+KYj+kwkMzXR0yU
+/UJF75G5k1M5BMV4BgLyr+5BkmFv/Vub8To6OTLeLp4AGL6QOKKm3vNiQIBIwKB
..... 중략
-----END RSA PRIVATE KEY-----
-->> 여기 빈칸 하나!!!

2009. 4. 7. 05:00

 

* / 는 최상위 디렉터리를 뜻함. 만약 찾고자 하는 디렉터리가 있다면 그걸로 대체

- 파일 이름에 foobar 가 들어간 파일 찾기
   find / -name "foobar" -print

- 특정 사용자(foobar) 소유의 파일을 찾기
   find / -user foobar -print | more

- 최근 하루동안에 변경된 파일을 찾기
   find / -ctime -1 -a -type f | xargs ls -l | more

- 오래된 파일(30일 이상 수정되지 않은 파일) 찾기
   find / -mtime +30 -print | more

- 최근 30일안에 접근하지 않은 파일과 디렉터리를 별도의 파일로 만들기
   find / ! ( -atime -30 -a ( -type d -o -type f ) ) | xargs ls -l > not_access.txt

- 하위 디렉터리로 내려가지 않고 현재 디렉터리에서만 검색하기
   find . -prune ...

- 퍼미션이 777 인 파일 찾기
   find / -perm 777 -print | xargs ls -l | more

- others 에게 쓰기(write) 권한이 있는 파일을 찾기
   find / -perm -2 -print | xargs ls -l | more

- others 에게 쓰기(write) 권한이 있는 파일을 찾아 쓰기 권한을 없애기
   find / -perm -2 -print | xargs chmod o-w
      또는
   find / -perm -2 -exec chmod o-w {} ; -print | xargs ls -l | more

- 사용자이름과 그룹이름이 없는 파일 찾기
   find / ( -nouser -o -nogroup ) -print | more

- 빈 파일(크기가 0 인 파일) 찾기
   find / -empty -print | more
      또는
   find / -size 0 -print | more

- 파일 크기가 100M 이상인 파일을 찾기
   find / -size +102400k -print | xargs ls -hl

- 디렉터리만 찾기?
   find . -type d ...

- root 권한으로 실행되는 파일 찾기
   find / ( -user root -a -perm +4000 ) -print | xargs ls -l | more

- 다른 파일시스템은 검색하지 않기
   find / -xdev ...

- 파일 이름에 공백이 들어간 파일 찾기
   find / -name "* *" -print

- 숨겨진(hidden) 파일을 찾기
   find / -name ".*" -print | more

- *.bak 파일을 찾아 지우기
   find / -name "*.bak" -exec rm -rf {} ;

- *.bak 파일을 찾아 특정 디렉터리로 옮기기
   mv `find . -name "*.bak"` /home/bak/

- 여러개의 파일에서 특정 문자열을 바꾸기
   find / -name "*.txt" -exec perl -pi -e 's/찾을문자열/바꿀문자열/g' {} ;

2009. 3. 31. 05:00

<td><nobr style="text-overflow:ellipsis;overflow:hidden;width:140px;">어쩌구 저쩌구 긴 글을 여기에 써요 하하하</nobr></td>
 
※ nobr : 독립적으로 사용하는 줄바꿈 금지 태그. 문자열이 긴경우 width 무시하고 계속 셀이 커짐
   
 - width : 140px : 140px을 기준으로 표현
 - overflow : hidden; 140px이 넘으면 보여주지 않음
 - text-overflow : ellipsis : 140px 이 넘는 문자열인 경우 자동으로 "..." 붙임.

 

2009. 3. 31. 05:00

Survey of AJAX/JavaScript Libraries

Please note these libraries appear in alphabetical order. If you're adding one to this list, please add it in alphabetical order rather than sticking it at the top.

There is another excellent and comprehensive list of libraries at EDevil's Weblog.

AjaxAnywhere

http://ajaxanywhere.sourceforge.net

License: Apache 2

Description: AjaxAnywhere is a simple way to enhance an existing JSP/Struts/Spring/JSF application with AJAX. It uses AJAX to refresh "zones" on a web page, therefore AjaxAnywhere doesn't require changes to the underlying code, so while it's more coarse than finely-tuned AJAX, it's also easier to implement, and doesn't bind your application to AJAX (i.e., browsers that don't support AJAX can still work.). In contrast to other solutions, AjaxAnywhere is not component-oriented. You will not find here yet another AutoComplete? component. Simply separate your web page into multiple zones, and use AjaxAnywhere to refresh only those zones that needs to be updated.

Pros:

  • Less JavaScript to develop and to maintain. Absence of commonly accepted naming convention, formatting rules, patterns makes JavaScript code messier then Java/JSP. It is extremely difficult to debug and unit-test it in multi-browser environment. Get rid of all those complexities by using AjaxAnywhere.
  • Easy to integrate. AjaxAnywhere does not require changing the underlying application code.
  • Graceful degradation and lower technical risk. Switch whenever you need between AJAX and traditional (refresh-all-page) behaviour of your web application. Your application can also support both behaviors.
  • Free open source license.

Cons:

  • AxajAnywhere? is not as dynamic as pure-JavaScript AJAX solutions. Despite that AjaxAnywhere will probably cover your basic needs, to achieve certain functionality you might need to code some JavaScript.
  • Today, you can only update a set of complete DHTML objects without breaking then apart. For example, you can update a content of a table cell or the whole table, but not the last row, for example. In later versions, we plan to implement partial DHTML update, as well.

AjaxTags component of Java Web Parts

http://javawebparts.sourceforge.net

License: Apache 2

Description: AjaxTags was originally an extended version of the Struts HTML taglib, but was made into a generic taglib (i.e., not tied to Struts) and brought under the Java Web Parts library. AjaxTags is somewhat different from most other Ajax toolkits in that it provides a declarative approach to Ajax. You configure the Ajax events you want for a given page via XML config file, including what you want to happen when a request is sent and when a response is received. This takes the form of request and response handlers. A number of rather useful handlers are provided out-of-the-box, things like updating a <div>, sending a simple XML document, transforming returned XML via XSLT, etc. All that is required to make this work on a page is to add a single tag at the end, and then one following whatever page element you want to attach an Ajax event to. Any element on a page can have an Ajax event attached to it. If this sounds interesting, it is suggested you download the binary Java Web Parts distro and play with the sample app. This includes a number of excellent examples of what AjaxTags can do.

Pros:

  • There is no Javascript coding required, unless you need or want to write a custom request/response handler, which is simply following a pattern.
  • Very easy to add Ajax functions to an existing page without changing any existing code and without adding much beyond some tags. Great for retroactively adding Ajax to an app (but perfect for new development too!)
  • Completely declarative approach to Ajax. If client-side coding is not your strong suite, you will probably love AjaxTags.
  • Has most of the basic functions you would need out-of-the-box, with the flexibility and extensibility you might need down the road.
  • Cross-browser support (IE 5.5+ and FF 1.0.7+ for sure, probably some older versions too).
  • Is well-documented with a good example app available.

Cons:

  • Because it's a taglib, it is Java-only.
  • Doesn't provide pre-existing Ajax functions like many other libraries, things like Google Suggests and such. You will have to create them yourself (although AjaxTags will make it a piece of cake!). Note that there are some cookbook examples available that shows a type-ahead suggestions application, and a double-select population application. Check them out, see how simple they were to build!
  • AjaxTags says absolutely nothing about what happens on the server, that is entirely up to you.
  • Might be some slight confusion because there is another project named AjaxTags at SourceForge. The AjaxTags in Java Web Parts existed first though, and in any case they have very different focuses. Just remember, this AjaxTags is a part of Java Web Parts, the other is not.

Dojo

http://dojotoolkit.org/

License: Academic Free License v 2.1.

Description: Dojo is an Open Source effort to create a UI toolkit that allows a larger number of web application authors to easily use the rich capabilities of modern browsers.

Pros:

  • Dev roadmap encompasses a broad range of areas needed to do browser-based app development -- Even the 0.1 release includes implementations of GUI elements, AJAX-style communication with the server, and visual effects.
  • Build system uses Ant, so core devs seem to be on friendly terms with Java.
  • Browser compatibility targets are: degrade gracefully in all cases, IE 5.5+, Firefox 1.0+, latest Safari, latest Opera
  • Most core parts of the system are unit tested (an unit tests are runnable at the command line)
  • Includes package system and build system that let you pull in only what you need
  • Comprehensive demo at http://archive.dojotoolkit.org/nightly/tests/

Cons:

DotNetRemoting Rich Web Client SDK for ASP.NET

http://www.dotnetremoting.com

License: - commercial license

Description: Rich Web Client SDK is a platform for developing rich internet applications (including AJAX). The product is available for .NET environment and includes server side DLL and a client side script

Pros:

  • No need for custom method attributes, special signatures or argument types. Does not require stub or script generation.
  • Available for .NET
  • Automatically generates the objects from the existing .Net classes.
  • Supports Hashtable and ArrayList? on the client
  • The client and the server objects are interchangeable
  • Can Invoke server methods methods from the client with classes as arguments
  • Very easy to program
  • Professional support

Cons:

  • Lacks out of the box UI components.

DWR

http://www.getahead.ltd.uk/dwr/

License: Apache 2.0

Description: DWR (Direct Web Remoting) is easy AJAX for Java. It reduces development time and the likelihood of errors by providing commonly used functions and removing almost all of the repetitive code normally associated with highly interactive web sites.

Pros:

  • Good integration with Java.
  • Extensive documentation.
  • Supports many browsers including FF/Moz, IE5.5+, Safari/Konq, Opera and IE with Active-X turned off via iframe fallback
  • Integration with many Java OSS projects (Spring, Hibernate, JDOM, XOM, Dom4J)
  • Automatically generated test pages to help diagnose problems

Cons:

  • Java-exclusive -- seems to be Java code that generates JavaScript. This limits its utility in non-Java environments, and the potential reusability by the community.

JSON-RPC-JAVA

http://oss.metaparadigm.com/jsonrpc/index.html

License: JSON-RPC-Java is licensed under the LGPL which allows use within commerical/proprietary applications (with conditions).

Description: JSON-RPC-Java is a key piece of Java web application middleware that allows JavaScript DHTML web applications to call remote methods in a Java Application Server (remote scripting) without the need for page reloading (as is the case with the vast majority of current web applications). It enables a new breed of fast and highly dynamic enterprise Java web applications (using similar techniques to Gmail and Google Suggests).

Pros:

  • Exceptionally easy to use and setup
  • Transparently maps Java objects to JavaScript objects.
  • Supports Internet Explorer, Mozilla, Firefox, Safari, Opera and Konqueror

Cons:

  • JavaScript Object Notation can be difficult to read
  • Possible scalability issues due to the use of HTTPSession

MochiKit

http://mochikit.com/

License: MIT or Academic Free License, v2.1.

Description: "MochiKit makes JavaScript suck less." MochiKit is a highly documented and well tested, suite of JavaScript libraries that] will help you get shit done, fast. We took all the good ideas we could find from our Python, Objective-C, etc. experience and adapted it to the crazy world of JavaScript.

Pros:

  • Test-driven development -- "MochiKit has HUNDREDS of tests."
  • Exhaustive documentation -- "You're unlikely to find any JavaScript code with better documentation than MochiKit. We make a point to maintain 100% documentation coverage for all of MochiKit at all times."
  • Supports latest IE, Firefox, Safari browsers

Cons:

  • Support for IE is limited to version 6. According to the lead dev on the project, "IE 5.5 might work with a little prodding."
  • Sparse visual effects library

Plex Toolkit

http://www.plextk.org - see http://www.protea-systems.com (and view source!) for sample site

License: - LGPL or GPL (optional)

Description: Open source feature-complete DHTML GUI toolkit and AJAX framework based on a Javascript/DOM implementation of Macromedia's Flex technology. Uses the almost identical markup language to Flex embedded in ordinary HTML documents for describing the UI. Binding is done with Javascript.

Pros:

  • Full set of widgets such as datagrid, tree, accordion, pulldown menus, DHTML window manager, viewstack and more
  • Markup driven (makes it easy to visually build the interface)
  • Interface components can be easily themed with CSS
  • Client side XSLT for IE and Mozilla
  • Well documented with examples.
  • Multiple remoting transport options - XMLHttpRequest?, IFrame (RSLite cookie based coming soon)
  • Back button support
  • Support for YAML serialization

Cons:

  • Lacks animation framework.

Prototype

http://prototype.conio.net/

License: MIT

Description: Prototype is a JavaScript framework that aims to ease development of dynamic web applications. Its development is driven heavily by the Ruby on Rails framework, but it can be used in any environment.

Pros:

  • Fairly ubiquitous as a foundation for other toolkits -- used in both Scriptaculous and Rico (as well as in Ruby on Rails)
  • Provides fairly low-level access to XMLHttpRequest

Cons:

  • IE support is limited to IE6.
  • No documentation other than the README: "Prototype is embarrassingly lacking in documentation. (The source code should be fairly easy to comprehend; I’m committed to using a clean style with meaningful identifiers. But I know that only goes so far.)" There's an unofficial reference page at http://www.sergiopereira.com/articles/prototype.js.html and some scattered pieces at the Scriptaculous Wiki.
  • Has no visual effects library (but see Prototype)
  • Has no built-in way of acessing AJAX result as an XML doc.
  • Modifications to Object.prototype apparently cause issues with for/in loops in interating through arrays. I could not find any information to indicate that this problem has been fixed.

Rialto

http://rialto.application-servers.com/

License: Apache 2.0

Description: Rialto is a cross browser javascript widgets library. Because it is technology agnostic it can be encapsulated in JSP, JSF, .Net or PHP graphic components.

Pros:

  • Technology Agnostic
  • Finition of widgets
  • Vision of the architecture
  • Tab drag and drop

Cons:

  • Scant documentation -- currently consists of two PDFs and a single Weblog entry.
  • Supports IE6.x and Firefox 1.x.
  • Documentation

Rico

http://openrico.org/

License: Apache 2.0

Description: An open-source JavaScript library for creating rich Internet applications. Rico provides full Ajax support, drag and drop management, and a cinematic effects library.

Pros:

  • Corporate sponsorship from Sabre Airline Solutions (Apache 2.0 License). This means that the code is driven by practical business use-cases, and user-tested in commercial applications.
  • Extensive range of functions/behaviors.

Cons:

  • Scant documentation -- currently consists of two PDFs and a single Weblog entry.
  • Supports IE5.5 and higher only. Also, no Safari support. From the Web site: "Rico has been tested on IE 5.5, IE 6, Firefox 1.0x/Win Camino/Mac, Firefox 1.0x/Mac. Currently there is no Safari or Mac IE 5.2 support. Support will be provided in a future release for Safari."
  • Has no built-in way of acessing AJAX result as an XML doc.
  • Drag-and-drop apparently broken in IE (tested in IE6)

SAJAX

http://www.modernmethod.com/sajax/

License: BSD

Description: Sajax is an open source tool to make programming websites using the Ajax framework — also known as XMLHTTPRequest or remote scripting — as easy as possible. Sajax makes it easy to call PHP, Perl or Python functions from your webpages via JavaScript without performing a browser refresh. The toolkit does 99% of the work for you so you have no excuse to not use it.

Pros: Supports many common Web-development languages.

Cons:

  • Seems limited just to AJAX -- i.e., XMLHttpRequest. No visual effects library or anything else.
  • Integrates with backend language, and has no Java or JSP support.

Scriptaculous

http://script.aculo.us/

License: MIT

Description: Script.aculo.us provides you with easy-to-use, compatible and, ultimately, totally cool! JavaScript libraries to make your web sites and web applications fly, Web 2.0 style. A lot of the more advanced Ajax support in Ruby on Rails (like visual effects, auto-completion, drag-and-drop and in-place-editing) uses this library.

Pros:

  • Well-designed site actually has some reference materials attached to each section.
  • Lots of neat visual effects.
  • Simple and easy to understand object-oriented design.
  • Although developed together with Ruby on Rails it's not dependent on Rails at all, has been used successfully at least in Java and PHP projects and should work with any framework.
  • Because of the large user-group coming from Ruby on Rails it has very good community support.

Cons:

  • No IE5.x support -- see Prototype -- Cons 1., above.

TIBCO General Interface (AJAX RIA Framework and IDE since 2001)

http://developer.tibco.com

TIBCO General Interface is a mature AJAX RIA framework that's been at work powering applicaitions at Fortune 100 and US Government organziations since 2001. Infact the framework is so mature, that TIBCO General Interface's visual development tools themselves run in the browser alongside the AJAX RIAs as you create them.

See an amazing demo in Jon Udell's coverage at InfoWorld?. http://weblog.infoworld.com/udell/2005/05/25.html

You can also download the next version of the product and get many sample applications from their developer community site via https://power.tibco.com/app/um/gi/newuser.jsp

Pros:

  • Dozens of types of extensible GUI components
  • Vector based charting package
  • Support for SOAP communication (in adiition to your basic HTTP and XML too)
  • Full visual development environment - WYSIWYG GUI layouts - step-through debugging - code completion - visual tools for connecting to services
  • An active developer community at http://power.tibco.com/GI

Cons:

  • Firefox support is in the works, but not released yet making this still something for enterprises to use where Internet Explorer is on 99.9% of business user desktops, but probably not for use on web sites that face the general population.

More info at http://developer.tibco.com

WebORB

http://www.themidnightcoders.com

License: Standard Edition is free, Professional Edition - commercial license

Description: WebORB is a platform for developing AJAX and Flash-based rich internet applications. The product is available for Java and .NET environments and includes a client side toolkit - Rich Client System to enable binding to server side objects (java, .net, web services, ejb, cold fusion), data paging and interactive messaging.

Pros:

  • Zero-changes deployment. Does not require any modifications on the server-side code, no need for custom method attributes, special signatures or argument types. Does not require stub or script generation.
  • Available for Java and .NET
  • One line API client binding. Same API to bind to any supported server-side type. Generated client-side proxy object have the same methods as the remote counter parts
  • Automatically adapts client side method arguments to the appropriate types on the server. Supports all possible argument types and return values (primitives, strings, dates, complex types, collections, data and result sets). Server-side arguments can be interfaces or abstract types
  • Includes a highly dynamic message server to allow clients to message each other. Server side code can push data to the connected clients (both AJAX and Flash)
  • Supports data paging. Clients can retrieve large data sets in chunks and efficiently page through the results.
  • Extensive security. Access to the application code can be restricted on the package/namespace, class or method level.
  • Detailed documentation.
  • Professional support

Cons:

  • Lacks out of the box UI components.

Zimbra

http://www.zimbra.com/

License: Zimbra Ajax Public License ZAPL (derived from Mozilla Public License MPL)

Description: Zimbra is a recently released client/server open source email system. Buried deep within this product is an excellent Ajax Tool Kit component library (AjaxTK?) written in Javascript. A fully featured demo of the product is available on zimbra.com, and showcases the extensive capabilities of their email client. A very large and comprehensive widget library as only avialable in commercial Ajax toolkits is now available to the open source community. Download the entire source tree to find the AJAX directory which includes example applications.

Pros:

  • Full support of drag and drop in all widgets. Widgets include data list, wizard, button, text node, rich text editor, tree, menus, etc.
  • Build system uses Ant and hosting is based on JSP and Tomcat.
  • Very strong client-side MVC architecture based; architect is ex-Javasoft lead developer.
  • Communications support for client-side SOAP, and XmlHttpRequest? as well as iframes.
  • Support for JSON serialized objects, and Javascript-based XForms.
  • Strong muli-browser capabilities: IE 5.5+, Firefox 1.0+, latest Safari
  • Hi quality widgets have commercial quaility since this is a commerical open source product.
  • Widget library is available as a separate build target set from the main product.
  • Debugging facility is built in to library, displays communications request and response.
  • License terms making it suitable for inclusion in other commercial products free of charge.

Cons:

  • Does not currently support: Keyboard commands in menus, in-place datasheet editing.
  • Does not support gracefull degradation to iframes if other transports unavailable.
  • Documentation is lacking, but PDF white paper describing widget set and drag and drop is available.

Others

Xajax

http://xajax.sourceforge.net/

Description: PHP-centric, looks very new

License: LGPL

SACK

http://twilightuniverse.com/projects/sack/

Description: New, limited feature set

License: modified X11


Last ten contributors to AjaxLibraries

출처 : Tong - 디밥님의 Web 2.0통


2009. 3. 31. 05:00
eclipse 빨리 실행하기
from: http://www.raibledesigns.com/page/rd/20030312

I changed my shorcut icon (Win2K) to have the following as it's target:

eclipse.exe -vmargs -Xverify:none -XX:+UseParallelGC -XX:PermSize=20M -XX:MaxNewSize=32M -XX:NewSize=32M -Xmx256m -Xms256m

Eclipse now starts in a mere 6 seconds (2 GHz Dell, 512 MB RAM). Without these extra settings, it takes 11 seconds to start. That's what I call a performance increase! (2003-03-12 09:32:04.0)

from: http://www.raibledesigns.com/comment.do?method=edit&entryid=065039163189104748672473500018

I tried this out, but the memory settings don't seem to have anything to do with startup time.
18 seconds - "eclipse.exe"
13 seconds - "eclipse.exe -vmargs -Xverify:none"
12 seconds - "eclipse.exe -vmargs -Xverify:none -XX:+UseParallelGC -XX:PermSize=20M -XX:MaxNewSize=32M -XX:NewSize=32M -Xmx96m -Xms96m"

It's only the Xverify:none parameter which has a noticeable effect on reducing startup time. On the java website I found that this parameter turns off bytecode verification ( http://developer.java.sun.com/developer/onlineTraining/Security/Fundamentals/Security.html ), although the default is supposedly "only verify classes loaded over the network".




2009. 3. 16. 05:00
http://ericmiraglia.com/blog/?p=140

Transcript:

Douglas Crockford: Welcome. I’m Doug Crockford of Yahoo! and today we’re going to talk about Ajax performance. It’s a pretty dry topic — it’s sort of a heavy topic — so we’ll ease into it by first talking about a much lighter subject: brain damage. How many of you have seen the film Memento? Brilliant film, highly recommend it. If you haven’t seen it, go get it and watch it on DVD a couple of times. The protagonist is Leonard Shelby, and he had an injury to his head which caused some pretty significant brain damage — particular damage as he is unable to form new memories. So he is constantly having to remind himself what the context of his life is, and so he keeps a large set of notes and photographs and even tattoos, which are constant reminds to him as to what the state of the world is. But it takes a long time for him to sort through that stuff and try to rediscover his current context, and so he’s constantly reintroducing himself to people, starting over, making bad decisions around the people he’s interacting with, because he really doesn’t know what’s going on around him.

If Leonard were a computer, he would be a Web Server. Because Web Servers work pretty much the same way. They have no short term memory which goes from one context to another — they’re constantly starting over, sending stuff back to the database, having to recover every time someone ‘talks’ to them. So having a conversation with such a thing has a lot of inefficiencies built into it. But the inefficiencies we’re going to talk about today are more related to what happens on the browser side of that conversation, rather than on the server.

So the web was intended to be sessionless, because being sessionless is easier to scale. But it turns out, our applications are mainly session full, and so we have to make sessions work on the sessionless technology. We use cookies for pseudosessions, so that we can correlate what would otherwise be unconnected events, and turn them into a stream of events — which would look more like a session. Unfortunately cookies enable cross site scripting or cross site request forge attacks, so it’s not a perfect solution. Also in the model, every action results in a page replacement, which is costly, because pages are heavy, complicated, multi-part things, and assembling one of those, and getting it across the wire can take a lot of time. And that definitely gets in the way of interactivity. So the web is a big step backwards in interactivity — but fortunately we can get most of that interactive potential back.

“When your only tool is a hammer, every problem looks like a webpage.” This is an adage you may have heard before — this is becoming less true because of Ajax. In the Ajax revolution, a page is an application which has a data connection to a server, and is able to update itself over time, avoiding a page replacement. So when the user does something, we send a JSON message to the server, and we can receive a JSON message as the result.

A JSON message is less work for the server to generate, it moves much faster on the wire because it’s smaller, it’s less work for the browser to parse and render than an HTML document. So, a lot of efficiencies are gained here. Here’s a time map of a web application. We start with the server on this side [motions left], the browser on the other [motions right], time running down. The first event is the browser makes a request — probably a URL or a GET Request — going to the server. The server respond with an HTML payload, which might actually be in multiple parts because it’s got images, and scripts, and a lot of other stuff in it. And it’s a much bigger thing than the GET request, so it takes lots of packets. It can take a significant amount of time. And Steve Souders has talked a lot about the things that we can do to reduce this time. The user then looks at the page for a moment, clicks on something, which will cause another request — and in the conventional web architecture, the response is another page. And this is a fairly slow cycle.

Now in Ajax — we start the same, so the page is still the way we deliver the application. But now when the user clicks on something, we’ll generate a request for some JSON data, which is about the same size as the former GET request, but the response is now much smaller. And we can do a lot of these now —so instead of the occasional big page replacement, we can have a lot of these little data replacements, or data updates, happening. So it is significantly more responsive than the old method.

One of the difficult things in designing such an application is getting the division of labour right: how should the application be divided between the browser and the server? This is something most of us don’t have much good experience with, and so that leads us to the pendulum of despair. In the first stage of the swing, everything happened on the server — the server looked on the browser as being a terminal. So all of the work is going on here, and we just saw the inefficiencies that come from that. When Ajax happened, we saw the pendulum swing to the other side — so everything’s happening on the browser now, with the view now that the server is just a file system.

I think the right place is some happy middle — so, we need to seek the middle way. And I think of that middle way as a pleasant dialogue between specialized peers. Neither is responsible for the entire application, but each is very competent at its specialty.

So when we Ajaxify an application, the client and the server are in a dialog, and we make the messages between them be as small as possible — I think that’s one of the key indications if you’re doing your protocol design properly. If your messages tend to be huge because, say, you’re trying to replicate the database, the browser — then I would say you’re not in the middle, you’re still way off to one end. The browser doesn’t need a copy of the database. It just needs, at any moment, just enough information that the user needs to see at that moment. So don’t try to rewrite the entire application in JavaScript — I think that’s not an effective way to use the browser. For one reason: the browser was not intended to do any of this stuff — and as you’ve all experienced, it doesn’t do any of this stuff very well. The browser is a very inefficient application platform, and if your application becomes bloated, performance can become very bad. So you need to try to keep the client programming as light as possible, to get as much of the functionality as you need, without making the application itself overly complex, which is a difficult thing to do.

Amazingly, the browser works, but it doesn’t work very well — it’s a very difficult platform to work with. There are significant security problems, there are significant performance problems. It simply wasn’t designed to be an application delivery system. But it got enough stuff right, perhaps by accident or perhaps by clever design, that we’re able to get a lot of the stuff done with it anyway. But it’s difficult doing Ajax in the browser because Ajax pushes the browser really hard — and as we’ll see, sometimes the browser will push back.

But before thinking about performance, I think absolutely the first thing you have to worry about is correctness. Don’t worry about optimization until you have the application working correctly. If it isn’t right, it doesn’t matter if it’s fast. But that said, test for performance as early as possible — don’t wait until you’re about to ship to decide to test to see if it’s going to be fast or not. You want to get the bad news as early in the development cycle as possible. And test in customer—like configurations — customers will have slow network connections, they’ll have slow computers. Testing on the developmer box on the local network to a developer server is probably not going to be a good test of your application. It’s really easy for the high performance of the local configuration to mask your sensitivity to latency problems.

Donald Knuth of Stanford said that “premature optimization is the root of all evil,” and by that he means ‘don’t start optimizing until you know that you need to.’ So, one place that you obviously know you need optimizing is in the start up — getting the initial page load in. And the work we’ve done here on exceptional performances is absolutely the right stuff to be looking at in order to reduce the latency of the page start up. So don’t optimize until you need to, but find out as early as possible if you do need to. Keep your code clean and correct, because clean code is much easier to optimize than sloppy code. So starting from a correct base, you’ll have a much easier time. Tweaking, I’ve found, for performance, is generally ineffective, and should be avoided. It is not effective, and I’ll show you some examples of that. Sometimes restructuring or redesign is required — that’s something we don’t like to do, because it’s hard and expensive. But sometimes that’s the only thing that works.

So let me give you an example of refactoring. Here’s a simple Fibonacci function. Fibonacci is a function for a value whose function is the sum of the two previous values, and this is a very classic way of writing it. Unfortunately, this recursive definition has some performance problems. So if I ask for the 40th Fibonacci number, it will end up calling itself over 300,000 times — or, 300,000,000 times. No matter how you try to optimize this loop, having to deal with a number that big, you’re not ever going to get it to a satisfactory level of performance. So here I can’t fiddle with the code to make it go faster — I’m going to have to do some major restructuring.

So one approach to restructuring would be to put in a memoizer — similar idea to caching, where I will remember every value that the thing created, and if I ever am asked to produce something for the same parameter, I can return the thing from the look up, rather than having to recompute it. So, here’s a function which does that. I pass it an array of values, and a fundamental function, it will return a function which when called, will look to see if it already knows the answer. And so it will return it, and if not, it will call itself, and pass its shell into that function, so that it can recurs on it. So using that, I can then plug in a simple definition of Fibonacci, here — and when I call Fibonacci on 40, it ends up calling itself 38 times. And it has kind of been doing a little bit more work in those 38 times, than it did on each individual iteration before, but we’ve got a huge reduction in the number — an optimization of about 10 million, which is significant. And that’s much better than you’re ever going to do by tweaking and fiddling. So sometimes you just have to change your algorithm.

So, getting back to the code quality. High quality code is most likely to avoid platform problems, and I recommend the Code Conventions for JavaScript Programming Language, which you can find at http://javascript.crockford.com/code.html. I also highly recommend that you use JSLint.com on all of your code. Your code should be going through without warnings — that will increase the likelihood that it’s going to work on all platforms. It’s not a guarantee, but it is a benefit. And it can catch a large class of errors that are difficult to catch otherwise. Also to improve your code quality, I recommend that you have regular code readings. Don’t wait until you’re about to release to read through the code — I recommend every week, get the whole team sitting at a table, looking at your stuff. It’s a really, really good use of your time. Experienced developers can lead by example, showing the others how stuff’s done. Novice developers can learn very quickly from the group, problems can be discovered early — you don’t have to wait until integration to find out if something’s gone wrong. And best of all — good techniques can be shared early. It’s a really good educational process.

If you finally decide you have to optimize, there are generally two ways you can think about optimizing JavaScript. There’s streamlining, which can be characterized by algorithm replacement, or work avoidance, or code removal. Sometimes we think of productivity in terms of the number of lines of code that we produce in a day, but any day when I can reduce the number of lines of code in my project, I think of that as a good day. The metrics of programming are radically different than any other human activity, where we should be rewarded for doing less, but that’s how programming works. So, these are always good things to do, and you don’t even necessarily need to wait for a performance problem to show up to consider doing these things. The other kind of optimization would be special casing. I don’t like adding special cases, I’ve tried to avoid it as much as possible — they add cruft to the code, they increase code size, increase the number of paths that you need to test. They increase the number of places you need to change when something needs to be updated, they significantly increase the likelihood that you’re going to add errors to the code. They should only be done when it’s proven to be absolutely necessary.

I recommend avoiding unnecessary displays or animation. When Ajax first occurred, we saw a lot of ‘wow’ demonstrations, like ‘wow, I didn’t know a browser could do that’ and you see things chasing around the screen, or chasing, or opening, or doing that stuff [gestures]. There are a lot of project managers, and project flippingss, who look at that stuff not understanding how those applications are supposed to deliver value — they get on that stuff instead, because it’s shiny and… But I recommend avoiding it. ‘Wow’ has a cost, and in particular as we’re looking more at widgeting as the model for application development, as we have more and more widgets, if they’re all spinning around on the screen, consuming resources, they’re going to interfere with each other and degrade the performance of the whole application. So I recommend making every widget as efficient as possible. A ‘wow’ effect is definitely worthwhile if it improves the user’s productivity, or improves the value of the experience to user. If it’s there just to show that we can do that, I think it’s a waste of our time, it’s a waste of the user’s time.

So when you’re looking at what to optimize, only speed up things that take a lot of time. If you speed up the things that don’t take up much time, you’re not going to yield much of an improvement. Here’s a map of some time — we’ve got an application which we can structure, the time spent on this application into four major pieces. If we work really hard and optimize the C code [gestures to shortest block] so that it’s using only half the time that it is now, the result is not going to be significant. Whereas if we could invest less but get a 10% improvement on the A code [gestures to longest block] that’s going to have a much bigger impact. So it doesn’t do any good to optimize that [gesture to block C], this is the big opportunity, this is the one to look at [gestures to block A].

Now, it turns out, in the browser, there’s a really big disparity in the amount of time that JavaScript itself takes. If JavaScript were infinitely fast, most pages would run at about the same speed — I’ll show you the evidence of that in a moment. The bottleneck tends to be the DOM interface — DOM is a really inefficient API. There’s a significant cost every time you touch the DOM, and each touch can result in a reflow computation, which can be very expensive. So touch the DOM lightly, if you can. It’s faster to manipulate new nodes before they are attached to the tree — once they’re attached to the tree, any manipulating of those nodes can result in another repaint. Touching unattached nodes avoids a lot of the reflow cost. Setting innerHTML does an enormous amount of work, but the browsers are really good at that — that’s basically what browsers are optimized to do, is parse HTML and turn it into trees. And it only touches the DOM once, from the JavaScript perspective, so even though it appears to be pretty inefficient, it’s actually quite efficient, comparatively. I recommend you make good use of Ajax libraries, particularly YUI — I’m a big fan of that. Effective coding reuse will make the widgets more effective.

So, this is how IE8 spends its time [diagram is displayed]. This was reported by the Microsoft team at the Velocity conference this year. So, this is the average time allocation of pages of the top 100 allexalwebpages. So they’re spending about 43% of their time doing layout, 27% of their time doing rendering, less than 3% of their time parsing HTML — again, that’s something browsers are really good at. Spending 7% of their time marshalling — that’s a cost peculiar to IE because it uses ActiveX to implement its components, and so there’s a heavy cost just for communicating between the DOM and JavaScript. 5% overhead, just messing with the DOM. CSS, formatting, a little over 8%. Jscript, about 3%. OK, so if you were really heroic, and could get your Jscript down to be really, really fast, most users are not even going to notice. It’s just a waste of time to be trying to optimize a piece of code that has that small an impact on the whole. What you need to think about is not how fast the individual JavaScript instructions are doing, but what the impact of those instructions have on the layout and rendering. So, this is the case for most pages on average — let’s look at a page which does appear to be compute bound.

This is the time spent for opening a thread on GMail, which is something that can take a noticeable amount of time. But if we look at the Jscript component, it’s still under 15%. So if we could get that to go infinitely fast, it still wouldn’t make that much of a difference. In this case, it turns out CSS formatting is chewing up most of the time. So if I were in the GMail team, running up this, I could be beating up my programmers saying ‘why is your code going so slow?’ or I could say ‘let’s schedule a meeting with Microsoft, and find out what we can do to reduce the impact of CSS expenditures in doing hovers, and other sorts of transitory effects,’ because that’s where all the time is going. So, that’s not a big deal. So you need to be aware of that when you start thinking about: ‘how am I going to make my application go faster?’

Now, there are some things which most language processors will do for you. Most compilers will remove common sub expressions, will remove loop invariants. But JavaScript doesn’t do that. The reason is that JavaScript was intended to be a very light, little, fast thing, and the time to do those optimizations could take significantly more time than the program itself was actually going to take. So it was considered not to be a good investment. But now we’re sending megabytes of JavaScript, and it’s a different model, but the compilers still don’t optimize — it’s not clear that they ever will. So there’s some optimizations it may make sense to make by hand. They’re not really justified in terms of performances, we’ve seen, but I think in some cases they actually make the code read a little better. So let me show you an example.

Here I’ve got a four loop, which I’m going to go through, a set of divs, and for each of the divs I’m going to change their styling — I’m going to change the color, and the border, and the background color. Not an uncommon thing to do in an Ajax application, but I can see some inefficiencies in this. One is, I have to compute the length of the array of divs on every iteration, because of the silly way that the fore statement works. I could factor that out — it’s probably not going to be a significant savings, but I could do that a bigger cost is, I’m computing divs by style on every itiration period. So I’m doing that three times per iteration — when I only have to do it once. And probably the biggest, depending on how big the length turns out to be, is that I’m computing the thickness parameter value on every iteration, and it’s constant, in the loop. So every time I compute that, except the first time, that’s a waste. I compute this loop this way. I create a border, which’ll precreate the thickness. Also, capture the number of divs. Then in the loop, I will also capture divs by style, so we’ll only have to get it once, and now I can change these things through that. To my eye, this actually read a little bit better — I can see border, yeah, this makes sense. I can see what I’m doing here. Do any of these changes affect the actual performance of the program? Probably not measurably, unless ‘n’ is really, really big. But I think it did make the code a little bit better and so I think this is a reasonable thing to do.

I’ve seen people do experiments where there are two ways you could say: a cat can eat a string. You need to use a plus operator, or you could do a ‘join’ on an array. And someone heard that ‘join’ is always faster, and so you see them doing cases where you concatenate two things together, they’ll make an array of two things and call ‘join’. This is strictly slower, this case, than that one. ‘Join’ is a big win if you’re concatenating a lot of stuff together. For example, if you’re doing an innerHTML build in which you’re going to build up, basically, a subdocument, and you’ve got a hundred strings that are going to get put together in order to construct that — in that case, ‘join’ is a big win. Because every time you call ‘+’, it’s going to have to compute the intermediate result of that concatenation, so it consumes more and more memory, and copies more and more memory as it’s approaching the solution. ‘Join’ avoids that. So in that case, ‘join’ is a lot faster. But if you’re just talking about two or three pieces being put together, ‘join’ is not good. So generally, the thing that reads the best will probably work, but there are some special cases where something like ‘join’ will be more effective. But again, it’s generally effective when ‘n’ is large — for small ‘n’, it doesn’t matter.

I recommend that you don’t tune for quirks. There are some operations which, in some browsers, are surprisingly slow. But I recommend that you try to avoid that as much as possible. There might be a trick that you can do which is faster on Browser A, but it might actually be slower on Browser B, and we really want to run everywhere. And the performance characteristics of the next generation of browsers may be significantly different than this one — if we prematurely optimize, we’ll be making things worse for us further on. So I recommend avoiding short term optimizations.

I also recommend that you not optimize without measuring. Our intuitions as to where our programs are spending time are usually wrong. One way you can get some data is to use dates to create timestamps between pieces of code — but even this is pretty unreliable. A single trial can be off by as much as 15ms, which is huge compared to the time most JavaScript statements are going to be running, so that’s a lot of noise. And even with accurate measurement, that can still lead to wrong conclusions. So measurement is something that has to be done with a lot of care. And evaluating the results also requires a lot of care.

[Audience member raises hand]

Douglas: Yeah? Oh, am I aware of any tools or instruments the JavaScript engine in the browsers so that you can get better statistics on this stuff? I’m not yet, but I’m aware of some stuff which is coming — new firebug plug—ins and things like that, which will give us a better indication as to where the time’s going. But currently, the state of tools is shockingly awful.

So, what do I mean when I talk about ‘n’? ‘N’ is the number of times that we do something. It’s often related to the number of data items that are being operated on. If an operation is performed only once, it’s not worth optimizing — but it turns out, if you look inside of it you may find that there’s something that’s happening more often. So the analysis of applications is strongly related to the analysis algorithms, and some of the tools and models that we can look at there can help us here.

So suppose we were working on an array of things. The amount of time that we spend doing that can be mapped according to the length of the array. So, there’s some amount of start up time, which is the time to set up the loop and perhaps to turn down the loop, on the fixed overhead of that operation. And then we have a line which descends as the number of pieces of data increases. And the slope of that line is determined by the efficiency of the code, or the amount of work that that code has to do. So a really slow loop will have a line like that [gestures vertically] and a really fast loop will have a line that’s almost horizontal.

So you can think of optimization as trying to change the slope of the line. Now, the reason you want to control the slope of the line is because of the axis of error. If we cross the inefficiency line, then a lot of the interactive benefits that we were hoping to get by making the user more productive, will be lost. They’ll be knocked out of flow, and they’ll actually start getting irritated — they might not even know why, but they’ll be irritated at these periods of waiting that are being imposed on them. They might not even notice, they’ll just get cranky using your application, which sets you up for some support phone calls and other problems — so you don’t want to be doing that. But even worse is, if you cross the frustration line. At this point, they become… they know that they’re being kept waiting, and it’s irritating, so satisfaction goes way down. But even worse than that is the failure line. This is the line where the browser puts up an alert, saying ‘do you want to kill the script?’ or maybe the browser locks up, or maybe they just get tired of waiting and they close the thing. This is a disaster, this is total failure. So you don’t want to do that either, so you want to not cross any of those lines, if you can avoid it — and you certainly never want to cross that one [gestures to failure line].

So to do that, that’s when you start thinking about optimizing: we’re crossing the line, we need to get down. One way we can think about it is changing the shape of the line. Sometimes if you change the algorithm, you might increase the overhead time of the loop — but in exchange for that, you can change the slope. And so, in many cases, getting a different algorithm can have a very good effect. Now, if the kind of data you’re dealing with has interactions in it, then you may be looking at an ‘n log n’ curve. In this case, changing the shape of the line won’t have much of a help. Or if it’s an n squared line, which is even worse — doubling the efficiency of this [gestures to point on line] only moves it slightly. So the number of cases that you can handle before you fail is only marginally increased by an heroic attempt to optimize — so that’s not a good use of your time.

So the most effective way to make programs faster is to make ‘n’ smaller. And Ajax is really good for that, Ajax allows for just—in—time data delivery — so we don’t need to show the user everything they’re ever going to want to see, we just need to have on hand what they need to see right now. And when they need to get more, we can get more in there really fast, by having lots of short little packets in this dialog.

One final warning is: The Wall. The Wall is the thing in the browser that when you hit it, it hurts really bad. We saw a problem in [Yahoo!] Photos, back when there was [Yahoo!] Photos [which was replaced by Flickr], where they were trying to do some…they had a light table, on which you could have a hundred pictures on screen. And then you could go to the next view, which would be another hundred pictures, and so on. And thinking they wanted to make it faster to go back and forth, they would cache all the structures from the previous view. But what they found was the next view — or, the first view, came up really fast, but the second view took a half second more, the next view took a second more, and then the next view a second and a half more, and so on. And pretty soon you reached the failure line. And it turned out that what they had done — intending to be optimizing, was actually slowing everything down. That the working set the browser was using, the memory it was using in order to keep all those previous views, which were being saved as full HTML fragments, was huge. And so the system was spending all of its time doing memory management, and there was very little time left for actually running the application. So the solution was to stop trying to optimize prematurely, and just try to make the basic process of loading one of these views as fast as possible. So the only thing that cached was the JSON data, which was pretty small, and they would rebuild everything every time — which didn’t take all that much time, because browsers are really good at that. And in doing that, they managed to get the performance down to a linear place again, where every view took the same amount of time.

These problems will always exist in browsers, probably. So the thing we need to be prepared to do is to back off, to rethink our applications, to rethink our approach. Because while the limits are not well understood, and not well advertised, they are definitely out there. And when you hit them, your application will fail, and you don’t want to do that. So you need to be prepared to rethink not only how you build the application, but even what the application needs to do — can it even work in browsers. For the most part, it appears to be ‘yes’, but you need to think responsively, think conversationally. The gaps don’t work very well in this device… So, that’s all I have to say about performance. Thank you.

The question was, did they have a way of flushing what they were keeping for each view? And it turned out they did. What they did was, they built a subtree in the DOM for each view of a hundred images, a hundred tiles, and they would disconnect it from the DOM and then build another one, and keep a pointer to it, so they could reclaim it. And then they’d put that one in there. And so they had this huge set of DOM fragments. And that was the thing that was slowing them down. Just having to manage that much stuff was a huge inefficiency for the browser. And they did that thinking they were optimizing — so that when you hit the back button, boom — everything’s there, and they can go back really fast. And then if you want to go forward again, you can go really fast. So they imagined they wanted to do that, and do that really effectively, but it turned out trying to enable that prevented that from working. So a lot of the things that happen in the browser are counterintuitive. So generally, the simplest approach is probably going to be the most effective.

That’s right, you don’t know what’s going to take the time — and so it becomes a difficult problem. You shouldn’t optimize until you know you need to. You need to optimize early, but you won’t be able to know until the application is substantially done. So, it’s hard.

Audience member: So it’ a matter of stay open to…

Douglas: That, and trying to stay in [...]. If you can keep testing constantly throughout the process, not wait until the end for everything to come together, that’s probably going to give you the best hope of having a chance to correct and identify performance problems.

Right, so the question is where to do paginations, essentially. Or caching. So, once approach is to have the server do the paginations, so it sends out one chunk at a time — and most websites work that way, because that’s the most responsive way to deliver the data. I can deliver 100 lines faster than I can deliver 1,000 lines, and so users like that — even though it means that they’re going to have to click some buttons to see the other 90% of it, people have learned to do that. The other approach is, take the entire data set and send that to the browser, and let the browser partition it out. And that has pretty much the same performance problems as the other approach, where we send all 1,000 in one page. What I recommend is doing it in chunks, and each chunk can be a pair of JSON messages, and request the chunks as you need them. That appears to be the fastest way the present the stuff to the user. Now, it’s harder to program that way — it’s easier for us if it’s one complete data set, and then we go ‘oh, we’ll just take what we need from that’. So that’s easy for us, but it does not give us the best performance. And as the data set gets bigger, it’s certain to fail.

Right. So, can we use canvass and CVS tricks to do well, is that a more effective way to accomplish that? Probably, at least in the few browsers that implement them currently. Over time, the browsers are promising to take better advantage of the graphics hardware, which standard equipment now on virtually all PCs — so it’s unlikely that we’ll be able to get that performance boost directly from JavaScript. So it’s likely that it’s going to be on the browser side, and those sorts of components. So eventually, that’s probably going to be a good approach — although it’s not clear how well that stuff’s going to play out in the mobile devices, and that’s becoming important too, so everything’s probably going to get harder and more complicated. That’s the forecast for 2009.


2009. 1. 12. 05:00

vi를 즐겨쓰는 사람들을 위한 이클립스를 위한 플러그인 - 나는 대만족^^ㅋ
등록하면 viplugin.license 가 생길텐데..아직 등록을 안해서..ㅡㅡ;
그래도 만족^^ㅋ
http://www.satokar.com/viplugin/


2008. 12. 16. 05:00


Using XML, XPath, and XSLT with JavaScript

There are several JavaScript XML libraries available to try to provide a cross-browser XML library. I've previously cited zXML in my Inline SVG article, there's also Sarissa and XML for <Script> and I'm sure others.

However, when I started using them I discovered various problems and limitations with them for what I needed to do. So, I decided to write my own cross-browser XML routines. I wanted an XML library that was as lightweight as possible, doing just what I needed and utilizing as much of the built in browser capabilities as possible.

In this article, I will first present a simple XML class which just holds the XML DOM object returned from an AJAX request and provides functions to get and change node values based on XPaths. Secondly, I will give a simple XSLT class to preform XSL Transformations.

The complete code for the XML and XSL library is available here

XML


First off is the constructor which determined if we will be using IE (ActiveX) functions or W3C standard functions for XML manipulation and either stores the XML DOM returned as the responseXML from an XMLHttpRequest(XHR) or creates an empty DOM object for later manipulation.
//
// XML
//
function XML(xmlDom) {
this.isIE = window.ActiveXObject;
if (xmlDom != null) {
this.xmlDom = xmlDom;
} else {
// create an empty document
if (this.isIE) {
Try.these (
function() { axDom = new ActiveXObject("MSXML2.DOMDocument.5.0"); },
function() { axDom = new ActiveXObject("MSXML2.DOMDocument.4.0"); },
function() { axDom = new ActiveXObject("MSXML2.DOMDocument.3.0"); },
function() { axDom = new ActiveXObject("MSXML2.DOMDocument"); },
function() { axDom = new ActiveXObject("Microsoft.XmlDom"); }
);
this.xmlDom = axDom;
} else {
this.xmlDom = document.implementation.createDocument("", "", null);
}
}
};

In case you're not getting the XML data from an XHR response, I also provided a load function to load an XML file from an URL.
// load
//
// Loads an XML file from an URL
XML.prototype.load = function(url) {
this.xmlDom.async = false;
this.xmlDom.load(url);
};

Next, I want to be able to find a single node in the XML DOM based on an XPath. The getNode function will do that for me.
// getNode
//
// get a single node from the XML DOM using the XPath
XML.prototype.getNode = function(xpath) {
if (this.isIE) {
var result = this.xmlDom.selectSingleNode(xpath);
} else {
var evaluator = new XPathEvaluator();
var result = evaluator.evaluate(xpath, this.xmlDom, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
}
return result;
};

More often, I don't need the actual DOM node object, but the value of that node, so I provide the getNodeValue a function to get the value of a node.
// getNodeValue
//
// get the value of a the element specified by the XPath in the XML DOM
XML.prototype.getNodeValue = function(xpath) {
var value = null;
try {
var node = this.getNode(xpath);

if (this.isIE &&amp; node) {
value = node.text;
} else if (!this.isIE && node.singleNodeValue) {
value = node.singleNodeValue.textContent;
}
} catch (e) {}

return value;
};

If you're just looking for a particular node/value, the previous functions are fine, but more often you need a group of node or node values (ex. all the book titles). So, the full JavaScript file also contains corresponding functions to get multiple nodes (getNodes) and node values as an array (getNodeValues).

At some point, you'll probably want to access this XML DOM as XML data (string), so we need a function to serialize the XML from the DOM to a String. The getNodeAsXml function will do that for you. If you pass in the root XPath ("/") it will serialize the complete XML file. Also, the included prettyPrintXml function can be used to escape the HTML characters.
// getNodeAsXml
//
// get the XML contents of a node specified by the XPath
XML.prototype.getNodeAsXml = function(xpath) {
var str = null;
var aNode = this.getNode(xpath);
try {
if (this.isIE) {
str = aNode.xml;
} else {
var serializer = new XMLSerializer();
str = serializer.serializeToString(aNode.singleNodeValue);
}
} catch (e) {
str = "ERROR: No such node in XML";
}
return str;
};


So far, we've only read the XML data we received. But we may also want to change the contents of the XML. So, here are the functions necessary to change existing node values (updateNodeValue), add new nodes/values (insertNode), and delete existing nodes (removeNode).

Note: the XPaths used for node insertions cannot be overly complex as I wanted to keep this library simple.
// updateNodeValue
//
// update a specific element value in the XML DOM
XML.prototype.updateNodeValue = function(xpath, newvalue) {
var node = this.getNode(xpath);
var changeMade = false;
newvalue = newvalue.trim();

if (this.isIE &&amp; node) {
if (node.text != newvalue) {
node.text = newvalue;
changeMade = true;
}
} else if (!this.isIE && node.singleNodeValue) {
if (node.singleNodeValue.textContent != newvalue) {
node.singleNodeValue.textContent = newvalue;
changeMade = true;
}
} else {
if (newvalue.length > 0) {
this.insertNode(xpath);
changeMade = this.updateNodeValue(xpath, newvalue);
}
}

return changeMade;
};

// insertNode
//
// insert a new element (node) into the XML document based on the XPath
XML.prototype.insertNode = function(xpath) {
var xpathComponents = xpath.split("/");
var newChildName = xpathComponents.last();
var parentPath = xpath.substr(0, xpath.length - newChildName.length - 1);
var qualifierLoc = newChildName.indexOf("[");
// remove qualifier for node being added
if (qualifierLoc != -1) {
newChildName = newChildName.substr(0, qualifierLoc);
}
var node = this.getNode(parentPath);
var newChild = null;
if (this.isIE && node) {
newChild = this.xmlDom.createElement(newChildName);
node.appendChild(newChild);
} else if ((!this.isIE) && node.singleNodeValue) {
newChild = this.xmlDom.createElement(newChildName);
node.singleNodeValue.appendChild(newChild);
} else {
// add the parent, then re-try to add this child
var parentNode = this.insertNode(parentPath);
newChild = this.xmlDom.createElement(newChildName);
parentNode.appendChild(newChild);
}
return newChild;
};

// removeNode
//
// remove an element (node) from the XML document based on the xpath
XML.prototype.removeNode = function(xpath) {
var node = this.getNode(xpath);
var changed = false;
if (this.isIE &&amp; node) {
node.parentNode.removeChild(node);
changed = true;
} else if ((!this.isIE) && node.singleNodeValue) {
node.singleNodeValue.parentNode.removeChild(node.singleNodeValue);
changed = true;
}
return changed;
};


You should now be able to fully read and manipulate XML using XPaths.

For any significant reformatting or processing of the XML, you'll probably want to utilize XSLT. So, next I'll provide a simple XSLT class. It will preload (into a DOM object) an XSL file in its constructor. This provides rapid transformations of new XML data passed in to it's transform function (including parameters).

First, the constructor which requires an URL pointing to the XSL file to be used for transformations. It does not accept a DOM object like the XML class did as it is assumed that the XSL (layout information) is more-or-less static and stored in a file whereas the XML data would most likely be dynamic and received via an XHR request.
//
// XSLT Processor
//
function XSLT(xslUrl) {
this.isIE = window.ActiveXObject;
if (this.isIE) {
var xslDom = new ActiveXObject("MSXML2.FreeThreadedDOMDocument");
xslDom.async = false;
xslDom.load(xslUrl);
if (xslDom.parseError.errorCode != 0) {
var strErrMsg = "Problem Parsing Style Sheet:\n" +
" Error #: " + xslDom.parseError.errorCode + "\n" +
" Description: " + xslDom.parseError.reason + "\n" +
" In file: " + xslDom.parseError.url + "\n" +
" Line #: " + xslDom.parseError.line + "\n" +
" Character # in line: " + xslDom.parseError.linepos + "\n" +
" Character # in file: " + xslDom.parseError.filepos + "\n" +
" Source line: " + xslDom.parseError.srcText;
alert(strErrMsg);
return false;
}
var xslTemplate = new ActiveXObject("MSXML2.XSLTemplate");
xslTemplate.stylesheet = xslDom;
this.xslProcessor = xslTemplate.createProcessor();
} else {
var xslDom = document.implementation.createDocument("", "", null);
xslDom.async = false;
xslDom.load(xslUrl);
this.xslProcessor = new XSLTProcessor();
this.xslProcessor.importStylesheet(xslDom);
}
};

Finally, the transform function will preform the XSL transformation and return the result. It accepts parameters to be passed to the XSL as an associative array of parameter name and value pairs.
// transform
//
// Transform an XML document
XSLT.prototype.transform = function(xml, params) {
// set stylesheet parameters
for (var param in params) {
if (typeof params[param] != 'function') {
if (this.isIE) {
this.xslProcessor.addParameter(param, params[param]);
} else {
this.xslProcessor.setParameter(null, param, params[param]);
}
}
}

if (this.isIE) {
this.xslProcessor.input = xml.xmlDom;
this.xslProcessor.transform();
var output = this.xslProcessor.output;
} else {
var resultDOM = this.xslProcessor.transformToDocument(xml.xmlDom);
var serializer = new XMLSerializer();
var output = serializer.serializeToString(resultDOM);
}
return output;
};


You should now be able to easily utilize XML and XSL on your web pages. An example usage of this XML/XSLT library would be to first build an XSLT object during the page initialization (onload).

xslProcessor = new XSLT(xslUrl);

Then, when XML responses are received from an AJAX request, process them. For example,
// get the XML data
try {
var xmlData = new XML(request.responseXML);
} catch (e) {
alert(request.responseText);
}

// get the username out of the XML
var userName = xmlData.getNodeValue('//userName');

// transform the XML to some HTML content
var newData = xslProcessor.transform(xmlData, {'param':'value'});
document.getElementById('someDiv').innerHTML = newData;


Update (February 27, 2007): I previously had a function in my XML class to generate valid HTML for the XML, but I've now modified it to use Oliver Becker's XML to HTML Verbatim Formatter with Syntax Highlighting stylesheet to format the XML. If that is not available, it will default to simply serialize the XML and convert the special characters. The code for this looks like:

/ Define a class variable which can be used to apply a style sheet to
// the XML for format it to HTML
XML.htmlFormatter = new XSLT("xsl/xmlverbatim.xsl");

// toHTML
//
// Transform the XML into formatted HTML
//
XML.prototype.toHTML = function() {
var html = null;
if (XML.htmlFormatter) {
html = XML.htmlFormatter.transform(this);
} else {
html = this.getNodeAsXml('/');
if (html != null) {
html = html.replace(/&/g, "&");
html = html.replace(/</g, "&lt;");
html = html.replace(/>/g, "&gt;<br/>");
}
}
return html;
}


As before, the complete package is available to download

Update (March 7, 2007): I have updated this package to utilize Google's AJAXSLT XSL-T implementation when a native JavaScript XSLT function is not available. I need to test it more before releasing it however.

http://blog.pothoven.net/2006/11/using-xml-xpath-and-xslt-with.html
2008. 12. 9. 05:00


보통 호출 방법
// 플래시 내부 함수 호출
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName]
    }
    else {
        return document[movieName]
    }
}

// 플래시에 내부에 있는 setSafecardMark 함수를 호출
thisMovie("safecard").setSafecardMark(index,length);

그러나 위의 방법들이 안된다.. 그러면 아래와 같이 한다.

1. Dom을 이용해 플래쉬에 접근하는 경우 E에서는 Object의 ID를 FF에서는 Embed의 ID를 사용하게 된다. 즉 아래와 같다.

     <object id="id1"><embed src="test.swf" id="id1" /></object>

위와 같이 설정하고

      document.getElementById('id1')

라고 하면 IE에서는 정상동작하겠지만 FF에서는 Object를 참조하기 때문에 오동작하게된다.

2. <form></form> 안에서 사용하면 안된다.
<form>
       form으로 둘러싸인 플래쉬 무비에서 ExternalInterface를 addCall 하면 해당 플래쉬의 ID를 찾을 수 없다는 에러를 발생시킨다.
</form>

이 문제는 아래의 코드를 사용해 해결할 수 있다. ExternalInterface를 사용하는 페이지에 아래의 로직을 인클루드시킨다.

<script type="javascript/text">
function ExternalInterfaceManager() {
   this.registerMovie = function(movieName) {


   if(!window.fakeMovies) window.fakeMovies = new Array();
      window.fakeMovies[window.fakeMovies.length] = movieName;
   }


   this.initialize = function() {
      if(document.all) {
         if(window.fakeMovies) {
            for(i=0;i<window.fakeMovies.length;i++) {
               window[window.fakeMovies[i]] = new Object();
            }

 

            window.onload = initializeExternalInterface;
         }
      }
   }
}


function initializeExternalInterface() {
   for(i=0;i<window.fakeMovies.length;i++) {
      var movieName = window.fakeMovies[i];
      var fakeMovie = window[movieName];
      var realMovie = document.getElementById(movieName);


      for(var method in fakeMovie) {
         realMovie[method] = function() {
            flashFunction = "<invoke name=\"" + method.toString() + "\" returntype=\"javascript\">" +       __flash__argumentsToXML(arguments, 0) + "</invoke>";this.CallFunction(flashFunction);
         }
      }


      window[movieName] = realMovie;
   }
}


</script>
   플래쉬를 표시하기 전 아래의 자바스크립트를 실행한다.
<script type="text/javascript">
//<![CDATA[var eim = new ExternalInterfaceManager();

eim.registerMovie("flashID");

eim.initialize();
//]]>
</script>

 

위의 방법보다 간단한 방법이라 소개된 자료
 function Flash(id, url, width, height)
{
     var str;
     str = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="' + width + '" height="' + height + '" id="' + id + '" align="middle">';
     str += '<param name="allowScriptAccess" value="sameDomain" />';
     str += '<param name="movie" value="' + url + '" /><param name="quality" value="high" /><param name="bgcolor" value="#ffffff" />';
     str += '<embed src="' + url + '" quality="high" bgcolor="#ffffff" width="' + width + '" height="' + height + '" id="'+ id +'" name="' + id + '" align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
     str += '</object>';
 
     document.write(str);
 
     //Flash의 ExternalInterface가 Form Tag내에서 오류나는 버그를 해결하는 코드
     eval("window." + id + " = document.getElementById('" + id + "');");
}


2008. 12. 3. 05:00
Web에서 자바스크립트의 사용은 웹을 유용하게 한다. 웹에서 사용하는 자바스크립트 이벤트는 다양하지만, 가장 많이 사용하는 것이 onClick 이벤트가 아닌가 한다. 사용자가 마우스로 클릭을 했을 때, 어떤 자바스크립트 함수를 호출하도록 하는 것이 onClick 이벤트이다.

특히 a(anchor) 태그와 함께 사용할 때, onClick 이벤트를 자주 사용하는데, 이 이유는 크게 세 가지가 있다.
  1. 이동되는 경로(URL)을 사용자에게 숨기기 위해서
  2. form 방식으로 페이지를 이동하여, 새로운 페이지에 값을 넘겨주기 쉽게 하기 위해서
  3. 페이지를 이동하기 전에 자바스크립트 함수를 호출하여, 메시지를 보여주거나 입력값을 체크하기 위해서

결국, a 태그가 페이지를 이동하는 역할을 함에도 불구하고 onClick를 사용하는 이유는 위에서 설명했다. 그러면 a 태그의 href를 무시하고 onClick 이벤트가 참조하는 자바스크립트 함수를 호출하는 방법은 여러가지가 있다. 먼저 자주 사용되는 것부터 확인해보자.

 1. <a href="javascript:alert('naver');"> Naver </a>
 2. <a href="#" onClick="alert('daum');"> Daum </a>
 3. <a href="javascript:void(0);"  onClick="alert('nate');"> Nate </a>

1번은 href의 값에 URL 대신 javascript 함수를 호출하도록 하였다. 클릭하면 바로 경고창이 뜨게 된다. 이 방법은 브라우저 하단의 회색의 상태바에 javascript:alert('naver');가 보인다.
2번은 자바스크립트가 호출하는 함수를 숨기기 위해 #을 사용했다. 하지만 이것은 함수에서 페이지가 이동하지 않으면, 브라우저가 이동할 곳을 잃어버리고 페이지의 상단으로 이동해버린다는 단점이 있다.
3번은 이것을 해결하기 위해 자바스크립트에서 Null과 마찬가지인 void(0)을 사용했다. 처음에는 이것의 문제를 몰랐는데, Internet Explorer 6 을 사용하는 사용자가 페이지가 이동하지 않는다고 이야기하여 이것의 문제를 알게 되었다. IE 7 이나 FireFox에서는 이상없이 처리되었다.

이 문제를 해결하기 위해 여러 곳을 찾아보다가 다음과 같은 해결책을 찾게 되었다.

 4. <a href="#" onClick="alert('dooji'); return false;"> dooji.com </a>
 5. <a href="javascript:void(0);"  onClick="alert('tistory'); return false;"> dooji.tistory.com </a>

바로 return false; 를 호출하는 함수 뒤에 추가하는 것이다. 이것은 href에 #을 사용해도 페이지 위로 이동하지 않는다. href의 값은 자신이 좋아하는 취향에 따라 적용하면 될 것 같다. 왜 이런 현상이 일어나는 지에 대해서는 좀 더 알아본 후에 적도록 하겠다.

2008. 10. 29. 05:00

Attribute definitions - http://www.w3.org/TR/REC-html40/interact/scripts.html
onload = script [CT]
The onload event occurs when the user agent finishes loading a window or all frames within a FRAMESET. This attribute may be used with BODY and FRAMESET elements.
onunload = script [CT]
The onunload event occurs when the user agent removes a document from a window or frame. This attribute may be used with BODY and FRAMESET elements.
onclick = script [CT]
The onclick event occurs when the pointing device button is clicked over an element. This attribute may be used with most elements.
ondblclick = script [CT]
The ondblclick event occurs when the pointing device button is double clicked over an element. This attribute may be used with most elements.
onmousedown = script [CT]
The onmousedown event occurs when the pointing device button is pressed over an element. This attribute may be used with most elements.
onmouseup = script [CT]
The onmouseup event occurs when the pointing device button is released over an element. This attribute may be used with most elements.
onmouseover = script [CT]
The onmouseover event occurs when the pointing device is moved onto an element. This attribute may be used with most elements.
onmousemove = script [CT]
The onmousemove event occurs when the pointing device is moved while it is over an element. This attribute may be used with most elements.
onmouseout = script [CT]
The onmouseout event occurs when the pointing device is moved away from an element. This attribute may be used with most elements.
onfocus = script [CT]
The onfocus event occurs when an element receives focus either by the pointing device or by tabbing navigation. This attribute may be used with the following elements: A, AREA, LABEL, INPUT, SELECT, TEXTAREA, and BUTTON.
onblur = script [CT]
The onblur event occurs when an element loses focus either by the pointing device or by tabbing navigation. It may be used with the same elements as onfocus.
onkeypress = script [CT]
The onkeypress event occurs when a key is pressed and released over an element. This attribute may be used with most elements.
onkeydown = script [CT]
The onkeydown event occurs when a key is pressed down over an element. This attribute may be used with most elements.
onkeyup = script [CT]
The onkeyup event occurs when a key is released over an element. This attribute may be used with most elements.
onsubmit = script [CT]
The onsubmit event occurs when a form is submitted. It only applies to the FORM element.
onreset = script [CT]
The onreset event occurs when a form is reset. It only applies to the FORM element.
onselect = script [CT]
The onselect event occurs when a user selects some text in a text field. This attribute may be used with the INPUT and TEXTAREA elements.
onchange = script [CT]
The onchange event occurs when a control loses the input focus and its value has been modified since gaining focus. This attribute applies to the following elements: INPUT, SELECT, and TEXTAREA.


- onUnload이벤트에서 새로고침과 창닫기 구분 - 
자동 로그아웃 등에 사용되는 onUnload 이벤트는 창을 닫는 것만이 아니라 새로고침에서도 발생한다.
이것을 구분하는 스크립트
function unload() {
    if( self.screenTop > 9000 ) {
           // 브라우저 닫힘
    } else {
        if( document.readyState == "complete" ) {
           // 새로고침
        } else  if( document.readyState == "loading" ) {
           // 다른 사이트로 이동
        }
    }
}

<body onUnload="javascript:unload();">
</body>




window.onload 이벤트를 등록하면 이미지나 css 파일이 다 로드된 후에 이벤트가 발생한다.
가끔 웹 서버 문제로 이미지 하나가 로딩이 늦어 질 경우 이벤트 발생 시점이 의도한 바와 차이가 생기게 된다.

이를 해결하기 위한 방법이 아래의 URL 에서 확인 가능하다.

The window.onload Problem - Solved!
* http://dean.edwards.name/weblog/2005/09/busted

window.onload (again)
* http://dean.edwards.name/weblog/2006/06/again/

위의 방법에 따라 onload 이벤트를 등록하게 될 경우 내부적으로 이벤트를 Push 하는 방법을 적용하고,
onunload 이벤트에 하나가 아닌 다수의 이벤트를 등록할 때 이를 관리하기 위한 부분도 추가하여
기존에 사용하던 이벤트 관리 스크립트를 업데이트 했다.

아래는 이벤트 관리 스크립트 소스.

/**
 * Class :: Event add, remove, registed event unload
 * File :: Event.js
 *
 * @classDescription    브라우저에 따른 이벤트 등록, 해제, 등록된 이벤트 모두 해제
 */
var EventManager = function() {
    constructor = this.__construct();
}

/**
 * window 객체에 load 이벤트 등록시 펑션 리스트를 등록
 */
var _OnLoadList = [];
/**
 * window 객체에 unload 이벤트 등록시 펑션 리스트를 등록
 */
 
var _UnLoadList = [];
/**
 * prototype of EventHandler class
 *  __construct
 * 
 *  _EventList
 * 
 *  add
 *  remove
 *  unload
 */
EventManager.prototype = {
    /**
     * window의 unload 이벤트에 EventHandler.unload 메소드를 등록
     *
     * @see #unload
     * @constructor
     */
    __construct: function() {
        var oThisObject = this;
       
        /* for Mozilla */
        if (window.addEventListener) {
            window.addEventListener("DOMContentLoaded", oThisObject.baseRun, false);
           
        /* for Safari */
        } else if (/WebKit/i.test(navigator.userAgent)) { // sniff
            var _timer = setInterval(function() {
                if (/loaded|complete/.test(document.readyState)) {
                    oThisObject.baseRun();
                }
            }, 10);
           
        /* for Internet Explorer */
        } else {
            var bInit = false;
           
            /*@cc_on @*/
            /*@if (@_win32)
                document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
               
                var oScriptLoad = document.getElementById("__ie_onload");
               
                oScriptLoad.onreadystatechange = function() {
                    if (this.readyState == "complete") {
                        oThisObject.baseRun();
                    }
                };
               
                bInit = true;
            /*@end @*/
           
        /* for Other */
            if (bInit == false) {
                window.onload = oThisObject.baseRun;
            }
        }
       
        this.add( window, 'unload_event', EventManager.prototype.unload );
    },
   
    /**
     * 페이지 종료시 등록된 이벤트를 해제하기 위하여 추가된 Event 목록
     *
     * @type {Array}        add 에서 데이터 추가
     */
    _EventList: [],
   
    /**
     * event 를 addEventListener 와 attachEvent 를 사용하여 등록 <br />
     * _EventList 에 등록된 이벤트를 배열로 저장
     *
     * @param {Object} setElement       HTML Object
     * @param {String} eventName        event name - on 을 접두어로 붙이지 않음
     * @param {Function} funcName       Exist function name
     */
    add: function( setElement, eventName, funcName ) {
        if ((setElement == window) && (eventName == 'load')) {
            _OnLoadList.push(funcName);
        } else if ((setElement == window) && (eventName == 'unload')) {
            _UnLoadList.push(funcName);
        } else {
            if ((setElement == window) && (eventName == 'unload_event')) {
                eventName = 'unload';
            }
           
            if ( window.addEventListener ) {
                setElement.addEventListener( eventName, funcName, false );
            } else {
                setElement.attachEvent( 'on' + eventName, funcName );
            }
           
            this._EventList.push({
                object: setElement,
                event:  eventName,
                func:   funcName
            })
        }
    },
   
    /**
     * event 를 removeEventListener 와 detachEvent 를 사용하여 해제
     *
     * @param {Object} setElement   HTML Object
     * @param {String} eventName    event name - on 을 접두어로 붙이지 않음
     * @param {String} funcName     Exist function name
     */
    remove: function( setElement, eventName, funcName ) {
        if ( window.removeEventListener ) {
            setElement.removeEventListener( eventName, funcName, false );
        } else {
            setElement.detachEvent( 'on' + eventName, funcName );
        }
    },
    /**
     * window.unload 이벤트시 _EventList 에 등록된 모든 이벤트를 해제
     */
    unload: function() {
        var sFunction = '';
       
        for ( var oEventData in _UnLoadList ) {
            sFunction = _UnLoadList[oEventData];
           
            if (sFunction == '______array') {
                continue;
            }
           
            sFunction.call();
        }
       
        _UnLoadList = []
       
        for ( var oEventData in this._EventList ) {
            this.remove( oEventData.object, oEventData.event, oEventData.func );
        }
    },
    /**
     * window.onload 에 등록한 function 을 모두 실행시킨다.
     */
    baseRun: function() {
        var sFunction = '';
       
        for ( var oEventData in _OnLoadList ) {
            sFunction = _OnLoadList[oEventData];
           
            if (sFunction == '______array') {
                continue;
            }
           
            sFunction.call();
        }
    }
}
var oEvent = new EventManager();
var Event = function() {
    return oEvent;
}

2008. 10. 29. 05:00

여기도 가볼 것. - http://mm.sookmyung.ac.kr/~sblim/lec/xml-int02/javascript/js02-02.htm
자바스크립트 이벤트 .....................................................


아주 중요한 이벤트!!!
이벤트란 모든 행위를 말하는 것으로 프로그램에서는 미리 사용자의 행위를 예측하여 미리 사용할 수 있도록 이벤트를 많이 준비해 놓고 있다.

예를 들어 사용자가 마우스를 클릭할 것이다.... 이건 click 이벤트로 준비!
이게 없다면 우리는 사용자가 마우스를 클릭했는지 부터 알아내야 다음 일을 할 수 있을 것이다. 고맙게도 click이 일어났다는 걸 자동으로 알 수 있으니 얼마나 고마운 일인가...

(Click, MouseOver, MouseOut, Submit...)

이벤트 핸들러란 ?

이러한 이벤트와 우리가 준비한 프로그램을 연결해 주는 구실을 한다

(onClick,onMouseOver,onMouseOut, onSubmit...)

* 그래서 우리가 할일은 이벤트가 일어났을 때 할 일을 준비하고
이벤트 핸들러에게 그 일을 하도록 연결해 두면 되는 것이다~~~


■ 이벤트의 종류와 의미 (이벤트핸들러는 이벤트에 on을 붙여 준다)

blur
포커스를 다른곳으로 옮길 경우
click 링크나 폼의 구성원을 클릭할 때
change 선택값을 바꿀 경우
focus 포커스가 위치할 경우
mouseover 마우스가 올라올 경우
mouseout 마우스가 떠날 경우
mousedown 마우스를 누를 경우
mousemove 마우스를 움직일 경우
mouseup 마우스를 눌렀다 놓을 경우
select 입력양식의 하나가 선택될 때
submit 폼을 전송하는 경우
load 페이지,윈도우가 브라우져로 읽혀질 때
unload 현재의 브라우저,윈도우를 떠날 때
error 문서나 이미지에서 에러를 만났을 때
reset 리셋 버튼이 눌렸을 때
dbclick 더블클릭시
dragdrop 마우스 누르고 움직일 경우
keydown 키 입력시
keypress 키 누를 때
keyup 키를 누르고 놓았을 때
move 윈도우나 프레임을 움직일 때
resize 윈도우나 프레임 사이즈를 움직일 때


■ 메서드

blur()
입력 포커스를 다른 곳으로 이동시킴
click() 마우스 버튼이 눌러진 것처럼 해줌
focus() 입력 포커스를 준 것처럼 해줌
submit() 폼의 submit 버튼을 누른 것처럼 해줌
select() 메소드 폼의 특정 입력 필드를 선택함


■ 속성

event.keyCode 누른 키의 ASCII 정수 값
event.x
문서 기준 누른 좌표의 left
event.y 문서 기준 누른 좌표의 top
event.clientX 문서 기준 누른 좌표의 left
event.clientY 문서 기준 누른 좌표의 top
event.screenX 콘테이너 기준 누른 좌표의 left
event.screenY 콘테이너 기준 누른 좌표의 top


■ 브라우저 객체별 이벤트 핸들러

선택 목록(SELECT)
onBlur, onChange, onFocus
문자 필드(TEXT) onBlur, onChange, onFocus, onSelect
문자 영역(TEXTAREA) onBlur, onChange, onFocus, onSelect
버튼(BUTTON) onClick
체크박스(CHECKBOX) onClick
라디오 버튼(RADID) onClick
링크 onClick, onMouseover
RESET 버튼(RESET) onClick
SUBMIT 버튼(BUTTON) onClick
DOCUMENT onLoad, onUnload
WINDOW onLoad, onUnload
폼(FORM) onSubmit

2008. 8. 7. 05:00
Dependency Walker 2.2

Dependency Walker is a free utility that scans any 32-bit or 64-bit Windows module (exe, dll, ocx, sys, etc.) and builds a hierarchical tree diagram of all dependent modules. For each module found, it lists all the functions that are exported by that module, and which of those functions are actually being called by other modules. Another view displays the minimum set of required files, along with detailed information about each file including a full path to the file, base address, version numbers, machine type, debug information, and more.
사용자 삽입 이미지

2008. 8. 7. 05:00
vim diff
사용자 삽입 이미지


winmerge
사용자 삽입 이미지


diff doc
사용자 삽입 이미지


2008. 7. 18. 05:00


http://www.popome.com/?p=28
2단계 : signal()

통신 프로그램 생각할때 먼저 떠올리는건 서버와 클라이언트 즉 리눅스와 윈도우 아니면 서버가 서버의 통신을 생각한다.
통신은 이렇게 두개의 프로그램 또는 다른 서버간에 통신뿐 아니라 1단계에서 말한 프로세서간 내부 통신도 매우 중요한 부분이다.

통신 프로그램을 짤때 단순히 클라이언트가 서버에 접속해서 데이타를 요청하고 받는 단순 구조인 경우라면 크게 신경을 안써도 되겠지만 만일 접속된 클라이언트간에 데이타를 주고 받는 상황이라면 내부 프로세서가 통신은 매우 중요한 부분이다.
게임 프로그램이나 메신저와 같이 클라이언트간에 데이타를 주고 받거나 또는 시스템 상에서 데몬의 종료나 환경 변수의 변경등을 알려주는 기능도 내부 통신이라고 할 수 있다.

아파치 웹서버의 파라메터나 도메인 정보가 바뀌었을때 데몬을 재 시작해도 상관없지만 보통의 경우는 killall -HUP httpd 이런식으로 해당 데몬에게 신호를 주는 방식도 있다.

내부 프로세서가 통신은 IPC라고 하는 칭하는데 3가지의 형태가 있다.
1. tcp, udp, pipe와 같이 데이타를 전송하는 방식
2. semaphore, mutex 와 같이 데이타 동기를 맞추는 방식
3. signal, wait 과 같이 신호를 전송하는 방식
더 많은 분류와 함수도 있겠지만 그 목적별로 나눈다면 위의 가지수가 될것이다.

이번에 설명하는 signal은 데모을 만들때 중요한 기능이므로 우선 설명하기로 한다.

예제 프로그램은 kill 호출이 되기전까지는 1초씩 기다리면서 무한루프를 도는 구조이다. SIGINT는 Ctrl+C를 막는 기능이고 SIGHUP은 일반적으로 프로그램에게 외부 환경 파일이 변경됨을 알려주는 기능으로 많이 사용한다. SIGTERM은 kill 신호를 받았을때 바로 죽지 않고 종료를 안전하게 처리하는 기능을 수행한다.

정확한 코딩방식으로는 signal로 받은 함수를 원상 복귀시키는 로직도 포함이 되어야 하지만 일반적으로 프로그램이 종료하면 자동 복귀가 되므로 생략하는 경우가 많다.

SIGCHILD는 fork로 생성된 프로세서가 종료될때 부모프로세서에게 종료됨을 알리고 부모가 wait도는 waitpid 형태의 함수를 호출해서 종료 상황을 인식할 수 있도록 프로그램을 짤 수 있다.

하지만 SIG_IGN 를 지정하면 해당 신호를 무시하여 간단히 처리하는것도 방법이다. 이렇게 처리하면 fork()로 생성된 child 가 종료시 defunct 형태로 ps 로 확인되는 zombi 프로세서의 생성을 자동적으로 처리해주는 기능을 수행하게 된다.

alarm 함수는 SIGALM을 호출하게 되어 타이머로서 이용할 수 있다.
block 모드로 동작하는 read, write, select 와 같은 함수에서 해당 기능을 이용하면 데이타 전송시 무한 대기로 빠지는 것을 방지할 수 있다.

단 kill -9 와 같이 강제 종료의 경우는 신호가 잡히지 않고 강제 종료가 되게 되므로 일반적인 kill 신호로 데몬을 종료시키면서 안전하게 종료하는 방법으로 개발해야 한다.

예제 프로그램을 실행하고나서 Ctrl+C 키를 누르거나 다른 텔넷창에서 kill -HUP process-id 과같이 테스트를 해볼 수 있다.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h> 

int sig = 0; 

void sigRtn( int s )
{
    sig = s;
    printf( "Receive signal : %d", sig );

void main()
{
    signal( SIGINT,  sigRtn );
    signal( SIGHUP,  sigRtn );
    signal( SIGTERM, sigRtn );
    signal( SIGALRM, sigRtn );
    signal( SIGCHILD, SIG_IGN ); 

    alarm( 10 ); 

    while( sig != SIGTERM )
    {
        sleep( 1 );
    } 

    printf( "Receive kill" );
}

2008. 7. 18. 05:00


Java Simple Daemon

http://kldp.net/projects/jsd/

뭐에 쓰는 물건인고?
Java Simple Daemon은 자바를 이용해서 데몬 프로그램을 작성하도록 도와주는 프레임워크이다(비록 프레임워크라고 부르기엔 너무도 작지만.. ^^).
가끔씩 특정 디렉토리에 들어오는 파일을 감시해서 파일이 들어오면 그 파일을 DB에 넣기만 하거나, 혹은 어떤 방식으로든 메시지를 받아서 받은 메시지를 가공해 다른 쪽에 메시지로 넘겨 주거나 하는 등의 역할을 하는 그런 프로그램을 자바로 짤 경우가 있다.
이러한 프로그램들은 일반적으로 그래픽 사용자 인터페이스(GUI)나 화면 출력이 필요 없이 파일로 로그만 남기고 자기 할 작업을 한다. 이러한 프로그램을 데몬(Daemon)이라 부른다.
자바로 이러한 데몬을 작성할 경우, 데몬을 실행시키는 것은 문제가 없다.


$ nohup java some.Daemon &
이러한 식으로 실행하면 된다. 헌데 문제는 종료이다. 프로그램과 의사 소통할 무슨 방법이 없기 때문에 Unix에서 ps -ef명령으로 "java" 프로세스를 찾아서 kill명령을 내리거나 윈도우의 경우에는 프로세스 종료를 시킬 수 밖에 없다. 이러한 문제를 해결하기 위해 만든 것이 Java Simple Daemon(이하 JSD)이다.

프로젝트 홈

프로젝트 개발 홈
사용자/개발자 게시판

다운로드
Java Simple Daemon 다운로드 목록
어찌 작동하는고?
원리는 단순하다. 데몬 역할을 하는 자바 클래스를 실행시켜주면서 쓰레드가 하나 떠서 사용자의 홈 디렉토리(Unix에서 $HOME 환경변수가 가리키는 디렉토리)에 특별한 파일이 존재하는지를 검사한다. 만약 그 특별한 파일이 존재한다면 JVM을 자동으로 종료시켜준다. JSD는 그 특별한 파일이 있는지 검사하는 역할과, 그 파일을 생성 시켜주는 역할을 한다.


덤으로, JSD는 데몬 클래스에 따라 락(Lock) 파일도 생성해준다. 홈 디렉토리에 락 파일이 존재할 경우, 데몬을 다시 띄우려고 하면 데몬 띄우기를 거부한다.

사용하기

데몬 클래스는 net.kldp.jsd.SimpleDaemon 인터페이스를 구현해야 한다.
public void startDaemon() : 데몬작업을 수행하는 메소드. 여기에 실제 작업 구현이 들어간다.
public void shutdown() : 데몬이 종료하기 전에 수행할 작업을 기록한다.
net.kldp.jsd.SimpleDaemonManager의 객체를 생성하고, 객체에 데몬 클래스를 등록해 준다.
net.kldp.jsd.SimpleDaemonManager.start()를 실행하면 데몬이 시작된다.
net.kldp.jsd.SimpleDaemonManager.shutdownDaemon()를 실행하면 데몬을 종료시키는 파일이 $HOME 디렉토리에 생성되어, 데몬을 종료시키게 된다.

예제 보기
아래 예제는 대책없이 화면에 시간을 출력하는 데몬이다.


데몬의 시작 : java net.kldp.jsd.sample.ShowTime
데몬의 종료(다른 콘솔 창에서) : java net.kldp.jsd.sample.ShowTime -shutdown
여기서 데몬을 종료하기 전에 다시 한번 데몬을 시작해보면 락 파일이 존재하기 때문에 실행을 거부하는 것을 볼 수 있다.
/*
 * Created on 2004. 11. 6.

 */
package net.kldp.jsd.sample;

import java.io.IOException;
import java.util.Date;

import net.kldp.jsd.IllegalSimpleDaemonClassException;
import net.kldp.jsd.SimpleDaemon;
import net.kldp.jsd.SimpleDaemonManager;

/**
 * SampleDaemon 예제.
 *
 * 현재 시간을 계속해서 보여주는 데몬이다.
 *
 */
public class ShowTime implements SimpleDaemon {

  public static void main(String args[]) {
    // -shutdown 옵션이 있을 경우 데몬을 종료시킨다.
    if (args.length > 0 && args[0].equals("-shutdown")) {
      System.out.println("ShowTime 종료시작.");
     
      try {

        SimpleDaemonManager sdm = SimpleDaemonManager.getInstance(ShowTime.class);
        sdm.shutdownDaemon();
      } catch (IOException e1) {
        e1.printStackTrace();
      } catch (IllegalSimpleDaemonClassException e) {
        e.printStackTrace();
      }
      return; // 프로그램 종료.
    }

    SimpleDaemonManager sdm = null;
   
    try {
      sdm = SimpleDaemonManager.getInstance(ShowTime.class);
      sdm.start();
    }  catch (Exception e) {
      e.printStackTrace();
    }
  }
 
  /**
   * 데몬 작업수행 : 현재 시간을 계속 보여준다.
   */
  public void startDaemon() {
    while (true) {
      Date now = new Date();
      System.out.println(now.toString());
      try {
        Thread.sleep(5000);
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
   
  }

  /**
   * ShowTime 종료시 실행할 내용들.
   */
  public void shutdown() {
    System.out.println("ShowTime을 종료합니다.");
  }
}

2008. 7. 18. 05:00


http://www.popome.com/?p=27

리눅스에서 TCP/IP 데몬 개발을 단계적으로 설명하고자 한다.

총 8단계에 걸쳐서 연재를 할 예정이고 각 단계별로 간단한 소스와 설명을 통해서 데몬 프로그램 기법을 정리할 예정이다.

모든 단계별 소스는 아주 간단하게 동작하도록 작성하였으나 보고 이해하기만 하면 절대로 그 의미를 100% 자신의 것으로 만들 수 없다. 앞으로 나오는 8단계는 영어 알파벳이라 생각하고 완젼히 외워야 한다. 복사해서 실행하지 말고 직접 타이핑 쳐서 컴파일 하기 바란다.

1단계 : fork()
2단계 : signal()
3단계 : thread
4단계 : 간단한 tcp 서버 데몬 #1
5단계 : 간단한 tcp 서버 데몬 #2
6단계 : 복수 클라이언트 접속용 tcp 서버 데몬 #1
7단계 : 복수 클라이언트 접속용 tcp 서버 데몬 #2
8단계 : 복수 클라이언트 접속용 tcp 서버 데몬 #3

물론 8단계가 완벽한 데몬형태가 되지는 않지만 8단계의 모든 소스를 조합한다면 충분히 완벽한 데몬을 제작하는데 어렵지 않을것이다.

1단계 : fork()

대부분의 네트웍 데몬을 공부하게 되면 가장 먼저 이해해야 하는 함수가 fork()다. 이 함수는 child processor를 생성하는 함수로 간단한 셈플을 아래 작성했다.

아래의 프로그램을 실행하면 재미있는 결과가 나올것이다.

물론 결과에서 프로세서 아이디에 해당하는 숫자(31332,31332) 는 실행하는 컴퓨터에 따라서 다르게 표시될것이다.

프로세서를 이해하지 못하는 사람이라면 if문으로 싸여진 출력문 중에서 조건이 맞는 하나만 출력되리라 생각되지만 실제로 실행결과는 두가지 모두 출력하게 된다.

하지만 fork() 위로는 출력문은 하나만 출력된다.
이는 fork() 가 호출되기 직전까지는 하나의 프로세서에서 fork()를 만나면서 두개의 프로세서로 나뉘어진다는 의미다.
손오공이 분신술로 2마리가 되는것과 같다.(^^)

fork()는 불려지는 순간 호출한 프로세서를 복제하게 되고 그 이후는 각각 따로 동작하게 된다는 점이 중요하다.

그래서 cnt값을 출격하는것이 Parent와 Child가 다르게 찍히게 되는것이다. Sleep이라는 함수를 이용해서 약간의 시간차 출력문으로 cnt의 변화값을 출력하게 되는데 초기 10의 값은 두 프로세서가 동일하게 가지고 있지만 부모프로세서는 중간에 0으로 변경을 하게 되어 마지막에 프로그램이 종료하는 순간 출력문은 10, 0 두가지 모두 출력하게 되는 것이다. 프로세서 번호를 따져보면 Parent와 Child가 초기에 같은 변수가 각각 따로 변함을 알게 된다.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> 

void main( int argc, char *argv[] )
{
        int      cnt = 10;
        pid_t   pid; 

        printf( “Call fork()” ); 

        pid = fork(); 

        printf( “fork() : %d“, pid ); 

        if ( pid )      // parent
        {
                cnt = 0;
                printf( “This is parent : %d“, getpid() );
                sleep( 5 );
                printf( “server end” );
        }
        else
        {
                printf( “This is child : %d, %d“, getpid(), getppid() );
                sleep( 3 );
                printf( “child end” );
        } 

        printf( “End process : %d %d“, getpid(), cnt );
}

=======================================
Call fork()
fork() : 31332
fork() : 0
This is child : 31332, 31331
This is parent : 31331
child end
End process : 31332 10
server end
End process : 31331 0
======================================


2단계 : signal()


통신 프로그램 생각할때 먼저 떠올리는건 서버와 클라이언트 즉 리눅스와 윈도우 아니면 서버가 서버의 통신을 생각한다.

통신은 이렇게 두개의 프로그램 또는 다른 서버간에 통신뿐 아니라 1단계에서 말한 프로세서간 내부 통신도 매우 중요한 부분이다.


통신 프로그램을 짤때 단순히 클라이언트가 서버에 접속해서 데이타를 요청하고 받는 단순 구조인 경우라면 크게 신경을 안써도 되겠지만 만일 접속된 클라이언트간에 데이타를 주고 받는 상황이라면 내부 프로세서가 통신은 매우 중요한 부분이다.

게임 프로그램이나 메신저와 같이 클라이언트간에 데이타를 주고 받거나 또는 시스템 상에서 데몬의 종료나 환경 변수의 변경등을 알려주는 기능도 내부 통신이라고 할 수 있다.


아파치 웹서버의 파라메터나 도메인 정보가 바뀌었을때 데몬을 재 시작해도 상관없지만 보통의 경우는 killall -HUP httpd 이런식으로 해당 데몬에게 신호를 주는 방식도 있다.


내부 프로세서가 통신은 IPC라고 하는 칭하는데 3가지의 형태가 있다.

1. tcp, udp, pipe와 같이 데이타를 전송하는 방식

2. semaphore, mutex 와 같이 데이타 동기를 맞추는 방식

3. signal, wait 과 같이 신호를 전송하는 방식

더 많은 분류와 함수도 있겠지만 그 목적별로 나눈다면 위의 가지수가 될것이다.


이번에 설명하는 signal은 데모을 만들때 중요한 기능이므로 우선 설명하기로 한다.


예제 프로그램은 kill 호출이 되기전까지는 1초씩 기다리면서 무한루프를 도는 구조이다. SIGINT는 Ctrl+C를 막는 기능이고 SIGHUP은 일반적으로 프로그램에게 외부 환경 파일이 변경됨을 알려주는 기능으로 많이 사용한다. SIGTERM은 kill 신호를 받았을때 바로 죽지 않고 종료를 안전하게 처리하는 기능을 수행한다.


정확한 코딩방식으로는 signal로 받은 함수를 원상 복귀시키는 로직도 포함이 되어야 하지만 일반적으로 프로그램이 종료하면 자동 복귀가 되므로 생략하는 경우가 많다.


SIGCHILD는 fork로 생성된 프로세서가 종료될때 부모프로세서에게 종료됨을 알리고 부모가 wait도는 waitpid 형태의 함수를 호출해서 종료 상황을 인식할 수 있도록 프로그램을 짤 수 있다.


하지만 SIG_IGN 를 지정하면 해당 신호를 무시하여 간단히 처리하는것도 방법이다. 이렇게 처리하면 fork()로 생성된 child 가 종료시 defunct 형태로 ps 로 확인되는 zombi 프로세서의 생성을 자동적으로 처리해주는 기능을 수행하게 된다.


alarm 함수는 SIGALM을 호출하게 되어 타이머로서 이용할 수 있다.

block 모드로 동작하는 read, write, select 와 같은 함수에서 해당 기능을 이용하면 데이타 전송시 무한 대기로 빠지는 것을 방지할 수 있다.


단 kill -9 와 같이 강제 종료의 경우는 신호가 잡히지 않고 강제 종료가 되게 되므로 일반적인 kill 신호로 데몬을 종료시키면서 안전하게 종료하는 방법으로 개발해야 한다.


예제 프로그램을 실행하고나서 Ctrl+C 키를 누르거나 다른 텔넷창에서 kill -HUP process-id 과같이 테스트를 해볼 수 있다.

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <signal.h>  


int sig = 0;  


void sigRtn( int s )

{

    sig = s;

    printf( "Receive signal : %d", sig );

}  


void main()

{

    signal( SIGINT,  sigRtn );

    signal( SIGHUP,  sigRtn );

    signal( SIGTERM, sigRtn );

    signal( SIGALRM, sigRtn );

    signal( SIGCHILD, SIG_IGN );  


    alarm( 10 );  


    while( sig != SIGTERM )

    {

        sleep( 1 );

    }  


    printf( "Receive kill" );

}


3 장 : thread


많은 데몬 개발 또는 통신 프로그램에서 fork()를 많이 이용한다.

하지만 필자는 fork보다는 thread 를 더 선호하는 편이다.


fork()는 단순 클라이언트의 경우에 상당히 유리하고 간단하게 개발할 수 있는 반면에 클라이언트간에 데이타 공유나 전송에는 오히려 더 어려운 코딩을 해야 하기 때문이다.


fork()가 진정한 child프로세서를 만드는 기법이라면 thread는 윈도우의 개발 방식과 상당히 유사하기 때문에 윈도우 클라이언트와 연동하는 모델의 서버를 개발한다면 thread쪽을 더 권장한다.


thread 가 fork()와 가장 다른점은 함수단위의 스래드 처리가 가능하기 때문에 global 변수나 기타 다른 함수의 데이타 공유가 가능하다는 점이다. 하지만 이런한 편의성은 두 스래드간에 동시 자료 접근으로 인한 결함도 야기된다. 예를 들어 두 스래드가 동시에 트리 또는 큐같은 메모리를 사용하게 되면 데이타의 연결고리가 끝어질 수 있는 단접이 있다. 이런 경우에 이후에 설명할 예정인 세마포 또는 뮤택스와 같은 동기 함수를 이용하는 코딩 기법이 필요하게 된다.


이번 예제에서 가장 중요한 포인트는 cnt라고 하는 global변수가 fork()방식으로 했을때 parent와 child가 각각 다른 변수로 인식되는 반면 thread에서는 같은 변수로 사용이 되는 접을 알수 있는 소스다.


아래의 소스를 실행해보면 cnt가 중간에 바뀌고 나서 thread에서 출력시에도 바뀐 값을 똑같이 출력하는것을 확인 할 수 있다.


다중 타스크 프로그램에서 fork와 thread어느쪽이 정답이하고는 할수 없다.

그건 while 이냐 for 냐의 구분과 비슷할 것이다.

하지만 이 두 방식의 차이를 정확히 이해한다면 데몬 개발에서는 상당히 편리한 코딩을 할 수 있게 된다.


#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <pthread.h>


int cnt = 0;


void *fun( void *arg )

{

printf( “This is child : %d“, getpid() );

sleep( 3 );

printf( “child end : %d“, cnt );


pthread_exit( NULL );

return 0;

}


void main( int argc, char *argv[] )

{

pthread_t t;

pthread_create( &t, NULL, fun, NULL );


cnt = 10;


printf( “This is parent : %d

“, getpid() );

sleep( 5 );

printf( “server end : %d

“, cnt );

}


=============================

This is child : 12325

This is parent : 12323

child end : 10

server end : 10



지난 3장까지는 기초적인 함수와 개녕이였고 이번 장부터는 실질 서버의 모습을 소개합니다.


첨부된 소스는 최소한의 코딩으로 만든 서버로 클라이언트가 접속한뒤 문자열을 송신하면 클라이어트에 받은 문자갯수를 돌려주고 종료하는 프로그램입니다.


테스트를 위해서는 telnet 을 클라이언트로 이용하시면 됩니다.

서버 기동시 포트번호를 파라메터로 입력하시면 되는데 주의할점은 1024 이하의 번호를 쓰기 위해서는 root로 로그인되어야 하고 이후번호의 경우는 무관합니다. linux의 기본 보안 정책이고..


tcp 서버를 만들기 위해서 가장 기본적으로 사용하는 함수는

socket, bind, listen, accept, recv, send, close


클라이언트라면

socket, connect, send, recv, close


서버의 경우는 bind, listen, accept 가 추가됩니다.


socket은 통신을 하기 위한 핸들을 생성하는 함수입니다.

파일 오픈과 동일한 기능이라고 생각하면 됩니다.

실재로 socket에서 리턴된 핸들에다 read, write와 같은 파일 명령으로 데이타를 송수신하여도 동일한 결과로 동작하게 됩니다.

close를 이용하는 걸 봐도 같다는걸 알수 있습니다.


bind는 뭔가를 묶는다는 뜻이므로 해당 어드레스와 포트를 시스템에게 예약하는 명령어입니다.


listen은 클라이언트가 젒속하도록 대기상태로 만드는 것입니다.

실제로 listen 이후부터는 클라이언트가 접속이 가능합니다.


일반적으로 listen( s, 5 )라고 5라는 숫자가 있는 리눅스의 기본 queue의 갯수가 5입니다. 변경할 필요도 없으면 크게 한다고 해서 실제로 커지지도 않습니다. 큐의 개념은 accept 로 빼내기전에 버퍼링되는 커넥션이라고 생각하면 됩니다.


accept라는것을 접속대기중인 클라이언트를 실제로 프로그램과 접속을 시켜주는 명령어입니다. accept의 리턴값이 소켓이고 새로운 소켓번호를 통해서 접속된 클라이언트와 송수신을 하게 되는 것입니다.


이후는 recv, read, send, write의 함수를 이용해서 통신을 하면됩니다.


샘플소스는 무조건 클라이언트를 기다라다가 접속이후 문자열을 기다리다가 문자열이 들어오면 문자열을 출력한뒤 클라이언트로 해당 문자열의 길이를 반환하고 종료하는 프로그랭입니다.


실제로 서버라기 보다는 수신 대기프로그램 및 수신 테스트 프로그램이라고 생각하면 됩니다.


#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include <unistd.h>  


#include <netdb.h>

#include <sys/socket.h>

#include <arpa/inet.h>  


int main( int argc, char *argv[] )

{

    if ( argc != 2 )

    {

        printf( "Usage : %s port", argv[0] );

        return -1;

    }  


    struct sockaddr_in  addr;  


    memset( &addr, 0, sizeof(addr) );  


    addr.sin_addr.s_addr = htonl( INADDR_ANY );

    addr.sin_port = htons( atoi( argv[1] ) );  


    int s = socket( AF_INET, SOCK_STREAM, 0 );  


    if ( !bind( s, (struct sockaddr *)&addr, sizeof(struct sockaddr_in) ) )

    {

        if ( !listen( s, 5 ) )

        {

            int S = accept( s, NULL, NULL );  


            if ( S != -1 )

            {

                char buff[1024];

                int  size;  


                memset( buff, 0, sizeof(buff) );

                size = read( S, buff, sizeof(buff) );  


                printf( "Read : %s", buff );  


                sprintf( buff, "Read %d bytes", size );

                write( S, buff, strlen(buff) );  


                close( S );

                printf( "Disconnect" );

            }

            else

            {

                printf( "accept error" );

            }

        }

        else

        {

            printf( "listen error" );

        }

    }

    else

    {

        printf( "bind error" );

    }  


    close( s );  


    return 0;

}





2008. 7. 8. 05:00
UTF-8 과 UINCODE 상호 변환


출처 : 국민대 컴퓨터공학부
http://nlp.kookmin.ac.kr
2008. 7. 8. 05:00

 

STL C++ 사용자 가이드
Rogue Wave STL C++ User Guide
http://ws1.kist.re.kr/doc/pgC++_lib/stdlibug/ug1.htm

한글판
http://idb.snu.ac.kr/~sjjung/stl/booktoc1.htm

http://www.omnistaronline.com/~fonin/projects/gnuitar/docs/install.html
http://www.gimp.org/windows/

http://www.gtk.org/download-windows.html


Windows Build Notes
To build GNUitar on Windows, you will need the following:

Microsoft Visual C++ 6.0 compiler (MSVC);
GTK 1.2 for Windows
Glib 1.2 for Windows
GNU libintl for Windows
GNU libiconv for Windows
All the software except MSVC is free and can be downloaded from the site http://www.gimp.org/win32
OR
http://www.gimp.org/~tml/gimp/win32


Currently, the exact links are:
http://www.gimp.org/~tml/gimp/win32/libintl-0.10.40-tml-20020904.zip
http://sourceforge.net/project/showfiles.php?group_id=25167 (general link for libiconv)
http://prdownloads.sourceforge.net/gettext/libiconv-1.8-w32-1.bin.zip?download
http://www.gimp.org/~tml/gimp/win32/glib-2.4.7.zip
http://www.gimp.org/~tml/gimp/win32/glib-dev-2.4.7.zip
http://www.gimp.org/~tml/gimp/win32/gtk+-1.3.0-20040315.zip
http://www.gimp.org/~tml/gimp/win32/gtk+-dev-1.3.0-20030115.zip
Please note that these links may change with the software updates. Another important note that since the first edition of this build guide, the original packages for GLib 2.2 and GTK 1.3 were removed. What I found are somewhat different versions, however I believe they should work. There is a certain doubt about compatibility of GLib 2.4 and libintl 0.10. In the case of any problems you should download all the latest packages for GLib and its dependencies (but NOT GTK 2.6 !)

You need to prepare your build environment, before you start to compile. Most of the packages above contain 2 important directories: "lib" and "include". Copy the contents of the "lib" directory of each package to the folder C:\Program Files\Microsoft Visual Studio\VC98\Lib (adjust this path to the real path where your MSVC installed), and the contents of the "include" directory to C:\Program Files\Microsoft Visual Studio\VC98\Include. Rename include\glib-2.0 to include\glib, lib\glib-2.0 to lib\glib, move \lib\include\gtk+\gdkconfig.h to include\gtkconfig.h. Now, you are ready to build the program. Launch MS Visual Studio, choose File->Open, select file gnuitar.dsp.
Select Build->Set Active Configuration and choose "Release" for Pentium Pro/II/III, or "Release 586" for Pentium processor, to make the benefit of Pentium CPU extended instructions set.
Press F7 to start build. If all the above were done correctly, you should not get error messages (please note that it produces few dozens of warnings, it is ok). If you get something like "Linker error: cannot resolve external symbols ...", this means that you've done something wrong when preparing build environment.


Command-line users should first run the file C:\Program Files\Microsoft Visual Studio\VC98\Bin\vcvars32.bat, to set environment variables, and then run:

nmake /f gnuitar.mak

If all went fine, you should pickup the file gnuitar.exe in the folder gnuitar\Release\ or gnuitar\Release 586\ depending on which configuration did you chose. Now, copy the gnuitar executable somewhere where you are going to keep it, and copy the files:

iconv.dll
libgdk-0.dll
libglib-2.0-0.dll
libgmodule-2.0-0.dll
libgtk-0.dll
libintl-1.dll

to the same folder as gnuitar.exe. Ready.
Windows Installation - Binary Package
GNUitar binary package does not require specific install on Windows - just unzip the package and run gnuitar.exe.

Linux - Install From RPM
RPM stands for RedHat Package Manager. Just download rpm file from the GNUitar site, and issue shell command as root:


rpm -i gnuitar-x.y.z.i386.rpm

Linux - Create Your RPM
You can create your own rpm package on Linux. To do so, you need first to install the package "rpm-build" from your Linux CD (first check does the /usr/src/redhat/ directory exist, if yes then you already have it installed). Then, copy the file gnuitar.spec to /usr/src/redhat/SPECS, and gnuitar-x.y.z.tar.gz to /usr/src/redhat/SOURCES. Changde dir to /usr/src/redhat/specs and issue


rpm -bb gnuitar.spec

prev"" #1 #2 next