Baocao

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

TRNG I HC BCH KHOA H NI VIN CNG NGH THNG TIN V TRUYN THNG

BI TP CHUYN
WEB V DCH V TRC TUYN

Tm hiu v lp trnh NodeJS Bch Vn Hi- CNTT1 20101464 Nguyn c Tun-CNTT2 20102430 Gio vin hng dn :

T Tun Anh

H NI
Ngy 23 thng 4 nm 2013

Mc lc

Li ni u
Cng ngh web ang c nhng bc pht trin mnh m. S pht trin bng n ca mng x hi v cc dch v thi gian thc thc y nhiu cng ngh mi ra i, gip tng cng kh nng tng tc. Trong phn nghin cu ny, chng em xin cp n mt cng ngh rt mi, NodeJS. c gii thiu t nm 2010,y l mt cng ngh mnh m gip xy dng cc ng dng hiu nng cao, c kh nng tng tc ngi dng mnh m. Do kin thc cn hn ch, bi bo co khng th trnh khi nhng sai xt. Chng em rt mong nhn c gp t thy. Chng em xin chn thnh cm n!

Chng 1 Cng ngh NodeJS


1.1 Cc m hnh Server

Trc ht ta tm hiu hot ng ca server. C nhiu cch phn loi server a trn cc c im khc nhau. Nhng ph bin nht vn l theo c im vo ra ca Server. Da trn c im ny, ta c th phn loi thnh 2 m hnh server: Synchronous IO Server Asynchronous IO Server

1.1.1

M hnh Synchronous IO Server

in hnh cho loi server ny l Apache. Khi client gi n server mt yu cu, server s da trn url yu cu tm ti nguyn tng ng. Server s i vo ra d liu.Ty vo ti nguyn , server c th gi mt chng trnh khc tin x l (v d php) v tr li kt qu cho client. p ng c yu cu cho nhiu client, server s s dng thread qun l mi yu cu ca client. tng cng hiu qu s dng thread, cc server thng s dng c ch spool thread. M hnh ny c th m hnh bi hnh v di y. Nh c th thy trong hnh ??, khi c mt yu cu c chp nhn. B phn phi yu cu s tm thread rnh ri v phn phi yu cu cho thread . Tuy nhin, m hnh ny vn cha nhng hn ch nht nh. l: Hn ch ca vic s dng lung: Vic s dng lung c nhng hn ch nht nh. Trc ht, s lng lung ti a c th to ra b gii hn bi kh nng ca CPU (vn C10K). Tip n l chi ph qun l lung cc k tn km c bit khi s lng lung ln(khi to lung, lp lch v chuyn i lung, hy b lung). Lng ph CPU do thi gian vo ra IO. Khi mt yu cu t client gi ti, server s phi c d liu c nh danh trong url, v chuyn n ti b tin x l. Trong thi gian vo ra, thread hon ton khng c tnh ton. Do vy hiu xut s dng CPU rt thp. Vic ng b gia cc thread: Trong trng hp mun ng b gia cc thread, vic ny cc k kh.

Hnh 1.1: M hnh synchronous IO Server

1.1.2

M hnh Asynchronous IO Server

Tiu biu cho m hnh server ny l Nginx. Hot ng theo c ch asynchronous IO. Vi cc server ny, c duy nht mt tin trnh hot ng.Trong trng hp mun tn dng a li ca server, tin trnh chnh c th c chia s thng qua cc tin trnh con. Khi yu cu gi t client n, server s gi yu cu cho b phn vo ra v yu cu v tip tc lng nghe cc yu cu khc t client. Khi kt thc vo ra, b phn vo ra gi tn hiu ngt ti server. Server s nhn d liu ny v tip tc x l. Trong trng hp ny, vic vo ra khng b block nh cc trng hp trn. Do vy, hiu xut s dng CPU tng nn. Hn na, trong trng hp ny, do ch c mt tin trnh duy nht, ta khng cn gp phi vn v thread v ng b gia cc Thread nh trong m hnh c gp phi na. M hnh ny c th c minh ha bi hnh di y:

1.2

Gii thiu NodeJS

NodeJS cng l mt server hat ng theo c ch asynchronous IO. Nhng im quan trng NodeJS cng l mt ngn ng lp trnh pha server. Nh trnh by trn, ta ch c mt tin trnh duy nht hot ng. c th lp trnh c, ta phi tr li 2 cu hi. Th nht l lm th no c th xc nh c cng vic server phi lm khi c mt ngt IO gi n. Th 2 l gii quyt vn ng cnh khi lp trnh. Trc ht, ta cng xem xt vn u tin.Gi s y l mt cng vic cn thc hin ca server: var post = db.query(SELECT * FROM posts where id = 1); // processing from this line onward cannot execute

Hnh 1.2: M hnh Asynchronous IO Server // until the line above completes doSomethingWithPost(post); doSomethingElse();

Trong v d ny server phi thc hin truy vn c s d liu. Sau khi thc hin song truy vn, ta mun server thc hin hm doSomethingWithPost(post) Trong m hnh Asynchronous IO, lm th no khi truy vn thc hin xong, server bit v thc hin hm ioSomethingWithPost(post) NodeJS qun l theo c ch Event callback. Event callback l khi nim ch hm s c gi khi c mt s kin xy ra. Code trn c th c vit li nh sau: callback = function(post) { doSomethingWithPost(post); }; db.query(SELECT * FROM posts where id = 1, callback); doSomethingElse(); Cch tip cn ny kh n gin v hp l. Ta s truyn hm cn thc thi nh mt tham s ca truy vn. Khi qu trnh IO kt thc, callback s c gi. Trong v d ny, hm callback y thc hin m s ln click vo mt nt. Bin clickCount y khng c khai bo trong hm. Do vy n chnh l bin ton cc. Do ti thi im khai bo, bin clickCount tn ti, nn y chnh l bin c tham chiu n khi callback c gi.

1.2.1

Mt kt qu benchmark

Trong phn ny ta cng lm mt v d benchmark n gin so snh hiu nng ca 2 m hnh

NodeJs vs Apache PHP benchmark Tt c cc bi so snh u c thc hin trong iu kin:

Server Apache 2.2.22 Apache Bench 2.3 Node.js v0.8.12 Laptop: Ubuntu: Release 12.04(precise) 32-bit KernelLinux 3.2.0-38-generic-pae GNOME 3.4.2 Hardware: Memory: 3.8 GB Processor: IntelCore i3-2330M CPU @ 2.20GHz x 4

Chng trnh ny c 2 ty chn quan trng l -n s yu cu v -c s lng yu cu ng thi v cui cng l url. Test vi Node.js: /usr/bin/ab -n 100000 -c 1000 http://localhost:8080/ Test vi Apache: /usr/bin/ab -n 100000 -c 1000 http://localhost/ Test vi chng trnh HelloWorld Chng trnh n gin dng test vi node.js server v Apache: hello.js

1 2 3 4 5 6 7 8 9 10

var sys = require(sys), http = require(http); http.createServer(function(req, res) { res.writeHead(200, { Server: nodeJS, Content-Type: text/html, Content-Length: 18, Connection: close, });

11 12 13

res.write(<p>Hello World</p>); res.end(); }).listen(8080);

index.php

1 2 3

<?php echo <p>Hello World</p> ?>

Sau qu trnh test ta thu c cc kt qu di bng sau:(Thi gian tnh theo n v giy) 100, 000 yu cu, 1000 yu cu ng thi x 1 2 3 4 5 Apache 25.972 27.908 26.708 29.893 25.980 NodeJs 14.467 14.643 15.854 16.724 14.389

th minh ha:

Test vi chng trnh tnh s PI Chng trnh s dng test: testPI.js

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21

var sys = require(sys), http = require(http); http.createServer(function(req, res) { res.writeHead(200, { Server: nodeJS, Content-Type: text/html, Content-Length: 18, Connection: close, }); var x = 3; var steps = 1000000; var pi = (1 - 1 / x); for (var i = 0; i < steps; i++) { x += 2; if (i % 2) { pi -= 1/x; } else { pi += 1/x;

22 23 24 25 26 27

} } pi *= 4; res.write(Pi = + pi); res.end(); }).listen(8080);

testPI.php

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19

<?php $x = 3; $steps = 1000000; $pi = (1 - 1 / $x); for ($i = 0; $i < $steps; $i++) { $x += 2; if ($i % 2) { $pi -= 1/$x; } else { $pi += 1/$x; } } $pi *= 4; echo "Pi = ". $pi; ?>

Sau qu trnh test ta thu c kt qu trong bng di y: x 1 2 3 4 5 Apache 26.001 27.134 26.801 28.201 27.040 NodeJs 3.181 3.198 3.423 4.214 3.426 th minh ha:

1.2.2

Lp trnh hng s kin trn server

Vi vic ra i NodeJS, cng dn n mt m hnh lp trnh mi trn server. l lp trnh hng s kin. Pha client, khi nim ny c th khng qu mi m. Trong ngn ng javascript, vic lp trnh gn lin vi cc s kin. Cc lp trnh vin s to cc s kin DOM v bt cc s kin ny v s l. Vi NodeJS, cch lp trnh cng nh vy. Ta cng bt cc s kin t pha client hoc cc s kin t h thng v phn hi. So vi cch lp trnh truyn thng, y l mt cch lp trnh kh th v, mi m. hiu r vn ny hn ta s tm hiu cc module c trnh by trong chng 3 ca bi bo 10

11

Chng 2 Ci t v qun l module trong NodeJS


2.1
2.1.1

Ci t NodeJS
Ci t NodeJS

ci t NodeJS bn c th truy cp v trang http://nodejs.org/download/ ti phin bn ph hp vi h iu hnh ca bn xung. Vi Windows: Bn ch cn chy file node-v0.8.18-x84.msi hoc node-v0.8.18-x64.msi ty theo h iu hnh ang s dng v tin hnh ci t bnh thng.

Vi Linux: Sau khi ti v gi package ca NodeJs ta tin hnh thc hin cc bc sau: 1. $ xzf node-v0.8.18.tar.gz 2. $ cd node -v0.8.18 3. $ ./configure 4. $ make

12

5. $ sudo make install Ngoi ra mt s bn phn phi linux cho php bn ti NodeJS thng qua package. thc hin iu , bn ch cn vo terminal v g lnh: $ apt-get install nodejs kim tra my ci nodeJS cha ta thc hin lnh: $ node -v

2.1.2

S dng NodeJs

Sau khi tin hnh ci t xong NodeJs chng ta bt u s dng Node. khi ng giao din dng lnh ca Node ta s dng cu lnh: $ node Tin hnh kim tra vic ci t v quan st Node ang lm g, ta s dng: > console.log(Hello World!) Hello World! > undefined Cng c th chy mt JavaScript t mt file. Nu to chng ta to mt file hello_world.js vi ni dung. console.log(Hello World!) Tin hnh file trn vi cu lnh: $ node hello_world.js Hello World

2.2
2.2.1

Qun l module trong NodeJS


Qun l module trong NodejS

Vi NodeJs ta c th m rng cc chc nng hng qua cc module. qun l chng, ta s dng mt phn mm ca bn th 3 l npm (Node Package control management). Thng tin v npm c th tm thy trang ch : http://npmjs.org. Npm c ci sn khi ci Nodejs.

13

1. lit k cc gi ta s dng lnh $ node ls [filter] Lit k tt c cc gi $ node ls Lit k tt c cc gi c ci t $ node ls installed Lit k tt c cc gi ang trng thi n nh(stable) $ node ls stable Lit k tt c cc gi theo tn $ node ls "tn hoc pattern" 2. ci t gi ta s dng lnh: $ npm install package[@filters] Ci gi express $ npm install express Ci gi express phin bn 2.0.0beta $ npm install express@2.0.0beta Ci gi phin bn ln hn 0.1.0 $ npm install express@">=0.1.0 3. g mt gi , ta dng lnh $ npm rm [-g] <package name>[@version] 4. xem thng tin v module no ta s dng lnh. $ npm view [@] [[.]...] 5. update cc module bng vic s dng cu lnh: $ npm update [-g] <package name>

2.3

Xy dng v s dng cc module

Trong phn ny, ta s tm hiu cch xy dng v s dng mt module cho nodeJS.
1

var module = require(path_to_module| module_name); Tham s truyn vo l tn module nu l mt core module c qun l qua npm. Trong trng hp module l mt module custom ca ngi dng, ta ch cn chi ra ng dn n file . Ngoi ra ta cng c th load cc module trong mt th mc. u tin Nodejs s kim tra xem c phi l mt packge hay khng thng qua kim tra mt file package.json. Cu trc file json s cha thng tin v file chnh ca package. V d:

1 2 3 4

{ "name": "myModule", "main": "./lib/myModule.js" }

14

Khi , Node s th load file path_to_module/lib/myModule.js Mt im quan trng cn lu tm l khi thc hin thao tc ny, ta cache module . Do vy khi vit nhiu ln np module, thc cht ch c mt hm c thc hin. truy cp vo cc thnh phn ca module, module cn phi xut thng tin ra thng qua lnh module.exports. V d:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

//test.js var level = 0; function loadGame(){ //code in here } function playGame(){ //code in here } module.exports.loadGame = loadGame; module.exports.playGame = payGame; module.exports.level = level; //app.js var test = require(./test.js); test.loadGame(); test.playGame(); console.log(test.level); Trong v d ny, trong module test, ta xut ra thng tin gm 2 hm v mt bin. Chnh v vy khi load module ny vo file app.js, ta c th s dng chng.

15

Chng 3 Lp trnh c bn NodeJS


3.1 Mt s module lm vic vo ra

Node cung cp mt s module lm vic trc tip vi file.

3.1.1

Module fs

y l module chnh gip ta c th thao tc vi tp.Module ny cung cp cc thao tc tp bao gm: To lp, i tn, xa tp Thao tc trn tp: m tp, c, ghi, ng tp Cp nht thi gian truy cp Thay i quyn s hu v quyn truy cp (trn h thng linux) ... Mt im ch l NodeJS h tr asynchronous IO v synchronize IO vi thao tc tp. Ta d dng nhn bit cc lnh ny thng qua tn gi. Cc lnh c file ng b s c Sync trong tn. V d: readFile(filename: string, data: mixed, [encoding], [callback:function]) readFileSync(filename: string, data: mixed, [encoding], [callback: function]) Ta cng c th kim tra thng tin v trng thi tp, th mc nh module ny. Mt s hm kim tra trng thi. fs.stat(filename: string, callback: function) : c thng tin trng thi, khi c xong gi hm callback. Tham s hm callback bao gm li (nu c) v object cha thng tin v file Cc hm kim tra kiu file: Kim tra cc kiu file . Cc kiu file ny tng ng trong h thng POSIX: isFile(); isDirrectory(): kim tra loi file l th mc. isBlockDevice(): kim tra loi file l thit b block. 16

isCharacterDevice(): kim tra thit b thuc loi c k t. isSymbolicLink(): file l link. isFIFO(): thit b c dng FIFO. isSocket(): socket.

3.1.2

Module path

Module ny cha cc tin ch gip xc nh v bin i ng dn ca tp. Mt s phng thc chnh: resolve: xc nh a ch tuyt i file da trn a ch tng i tp vi mt a ch tuyt i join: ni a ch vi nhau

3.2
3.2.1

Mt s module v mng
HTTP & HTTPS

Module HTTP l tp hp cc thao tc qua mng . Module ny gm c cc lp: http.Server: lp server http.ServerRequest : cho php biu din thng tin truy vn ti server. http.ServerResponse : lp biu din cc thng tin tr v t server. http.ClientRequest: lp biu din yu cu d liu.

HTTP l mt trong nhng thnh phn quan trng nht gip Nodejs hot ng nh mt Web Server. HTTP module cung cp phng thc createServer gip to ra mt th hin ca lp HTTP Server. Ngoi ra c mt s s kin v cu trc d liu thc hin cc callback.

17

http.Server Phng thc listen trong lp ny thit lp thng tin cho server nh cng, tn host, ng dn,.. Phng thc close nhm ng li server. Ngoi ra mt http Server s c cc s kin c bn sau: request : S kin s c kch hot mi khi c mt yu cu (request) ti server. Tham s ca hm callback gm : req : mt th hin ca lp http.serverRequest, cha thng tin yu cu t my client res : mt th hin ca lp http.serverResponse, cha thng tin tr v do my ch to ra connection: S kin c kch hot khi c mt lung d liu TCP xut hin. Ch rng vi mt lin kt TCP c th gm nhiu request. close: Khi server ng checkContinue: S kin c kch hot khi c 100 kt ni lin tip. Mc ch ca s kin ny gip lp trnh vin tng kh nng iu khin . Mc nh, nu s kin ny khng c ci t, 100 kt ni ny s c p ng. connect : S kin c kch hot khi c mt kt ni http CONNECT .Nu s kin ny khng c lng nghe, mc nh cc kt ni s b ng li. Tham s truyn vo callback gm: request: tham s ca request. socket: socket gia server v client. head: mt th hin ca lp Buffer, gi u tin ca .., thng c trng. upgrade : s kin c kch hot khi client c yu cu http upgrade. clientError: s kin c kch hot khi kt ni server v client tht bi.

3.2.2

Lp http.ServerRequest

Lp ny c to ngm nh bi server, c truyn nh mt tham s nh ta thy trong s kin request ca mt Server. Lp ny thc thi giao din ca Readable Stream k tha EventEmitter. Cc s kin c bn ca lp ny : data: s kin c kch hot khi nhn c cc on tin. Cc on tin ny l mt xu nu kiu m ha xc nh thng qua phng thc setEncoding hoc mt Buffer nu khng xc nh. end: s kin c kch hot vi ngha khng cn gi tin no na 18

close: s kin bo ng kt ni Ngoi ra lp ny cn mt s trng gip cung cp thm cc thng tin v request: method: phng thc yu cu : GET/POST/.. url: xu biu din cc yu cu (v d: ?id=1& type=2) httpVersion: phin bn version trailer: HTTP trailers headers: i trng cha tt c cc thng tin trng header ca request

Lp http.serverResponse y l lp c to ra do server khi c s kin request. Cu trc lp n c th hin nh hnh bn. Trong , mt s phng thc quan trng: writeHeader: thit lp thng tin header tr v cho client write : vit thng tin tr d liu tr v cho client. End : tn hiu bo truyn xong d liu cho server

19

http Client Mt trong cc c im quan trng ca Nodejs l pha server c th thc hin cc yu cu HTTP ti cc a ch khc nh mt my khch. iu ny c bit hu ch trong trng hp mun duy tr kt ni gia cc server. to mt yu cu HTTP ta thc hin thng qua lnh :
1

http.request(options: String, callback: function); Options l mt xu hoc mt i tng. Trong trng hp l i tng n s c t ng chuyn thng qua hm url.parse(). Mt s ty chn cho option: host: tn min hoc IP mun kt ni n. Mc nh, tn min l localhost port: cng kt ni method: phng thc HTTP (GET, POST,..). Mc nh phng thc kt ni l GET path: ng dn yu cu headers: cc thng tin headers Agent: user-agent ca my. y l mt th hin ca lp http.Agent V d sau minh ha cho vic thc hin mt yu cu tm kim ti Google:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

var http = require(http); var query = Nodejs Information; var opts = { host : google.com, port : 80, path: /search?q= + query, method: GET }; var req = http.request(opts, function(res){ console.log(res); //display response information res.setEncoding(utf8); res.on(data, function(data){ console.log(data); } }); req.end(); //send request y l kt qu khi thc hin xong chng trnh: Ngoi ra bn cng c th s dng http.get() trong trng hp phng thc HTTP ch l GET, cch s dng cng tng t nh trn.

20

3.2.3

Net

Module net l lp bao ca module http. Module ny cho php thit lp v to cc TCP server. N cha ng cc phng thc cho vic to c mt server v client. Chng ta c th s dng module ny vi require(net); Mt s phng thc ca module Net: net.createServer([options], [connectionListener]) To ra mt TCP server mi. Thamm s connectionListener c t ng thit lp vic bt s kin "connection". options l mt i tng vi mc nh true
1 2 3 4 5 6 7 8 9 10 11 12 13

var net = require(net); var server = net.createServer(function(c) { //connection listener console.log(server connected); c.on(end, function() { console.log(server disconnected); }); c.write(hello\r\n); c.pipe(c); }); server.listen(8124, function() { //listening listener console.log(server bound); }); net.connect(options, [connectionListener]) net.createConnection(options, [connectionListener]) Xy dng mt i tng socket mi v m socket nht nh. Khi socket c thnh lp, s kin connect s c sinh ra. Vi TCP sockets, i s options c i tng c t: 21

port: Port ca client kt ni (Required). host: Host ca client kt ni ti, mc nh l localhost. localAddress: Giao din a phng rng buc cc kt ni. y l mt v d:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

var net = require(net); var client = net.connect({port: 8124}, function() { //connect listener console.log(client connected); client.write(world!\r\n); }); client.on(data, function(data) { console.log(data.toString()); client.end(); }); client.on(end, function() { console.log(client disconnected); }); net.connect(options, [host], [connectionListener]) net.createConnection(options, [host], [connectionListener]) To ra mt TCP kt ni t port trong host. Nu host b b qua, localhost s c chn gi nh. Tham s connectListener s c thm vo nh vic bt s kin cho s kin "connect" net.connect(path, [connectListener]) net.createConnection(path, [connectListener]) To ra unix socket kt ni theo path. Tham s connectListener s c thm vo nh vic bt s kin cho s kin "connect".

3.2.4

URL & QueryString

y l 2 module tin ch h tr cho vic x l URL v cc truy vn. Module URL gip cho vic x l URL. Vi module ny ta c th tch xu URL thnh i tng biu din thng tin: host, hostname, querystring... URL cung cp 3 phng thc x l xu: parse: Chuyn t xu truy vn thnh mt i tng cha thng tin v url. Cc thng tin gm: protocol : giao thc kt ni hostname : tn host, s dng khi khng c thng tin trng host host: thay th cho hostname v port 22

pathname: ng dn search: thnh phn biu din yu cu ni dung tm kim l query query: ni dung tm kim hash: phn thng tin bt u bi du # format: chuyn t i tng thnh url resolve(baseURL: String, href: String) : xy dng xu biu din url t 2 thnh phn based URL v href. V d ta c xu c bn "http://google.com/test" v href l "/search?q=nodejs", xu tr v s l "http://google.com/search?q=nodejs" Ta c v d cho vic chuyn i xu truy vn:

Lp QueryString cung cp cc cng c gip x l xu truy vn. Lp ny cung cp mt s phng thc c bn sau:

stringify(obj: Object, [sep: String], [eq]) : Chuyn mt i tng biu din truy vn thnh mt xu. Mc nh Node s dng du ngn cch gia cc truy vn l du & v biu din gn gi tr bng du =. Ta c th ty chnh cc du ny nu cn parse(str,[sep: String],[eq: String],[options: Object]): Chuyn xu thnh i tng biu din truy vn phng thc escape() v unescape(): 2 phng thc ny hot ng nh phng thc stringify v parse nhng c th c ghi nu cn thit. Ta c v d sau:

23

1 2 3 4 5 6 7 8 9 10 11

querystring.parse(foo=bar&baz=qux&baz=quux&corge) // returns { foo: bar, baz: [qux, quux], corge: } querystring.stringify({ foo: bar, baz: [qux, quux], corge: }) // returns foo=bar&baz=qux&baz=quux&corge=

3.2.5

DNS

Chc nng module ny l gip phn gii tn min t tn min sang a ch IP v ngc li. Module ny h tr c phn gii da trn IPV4 v IPV6.

3.3
3.3.1

Mt s module cng c
Console

y l module ton cc, tc ta khng cn phi np module chy c cc hm m n cung cp. Module ny cung cp mt i tng console gip ta c th in ra cc thng tin. V d: console.log(hello world); Trong trng hp mun ghi thng bo li, ta s dng lnh warn: in du vt, ta dng hm : console.trace();

3.3.2

Util

Module ny chc nng tng t nh console nhng mnh m hn. Mt s hm thng dng: util.format(format,[]): nh dng vn bn hin th ra tng t nh hm printf trong C util.debug(string: str): block tin trnh hin ti v in xu str ra stderr 24

util.inspect(obj: object, [option: object]): tr v biu din xu ca i tng. y l mt cng c hu hiu trong trng hp mun debug thng tin.Mt s ty chn khi gi hm ny: showHidden: thit lp hin th vi cc i tng khng c tnh cht lit k depth: gii hn xu kim tra colors: hin th mu sc cho kt qu util.isArray: dng kim tra i tng truen vo c phi l mt mng hay khng

3.3.3

Event Emitter

Trong Node c nhiu i tng c th sinh ra nhiu s kin. Chng hn nh, mt TCP server c th sinh ra mt s kin "connect" trong mi ln my client kt ni ti. emitter.addListener(event, listener) emitter.on(event, listener) Thm mt listeners vo cui mng listener cho s kin c c t.
1 2 3

server.on(connection, function (stream) { console.log(someone connected!); }); emitter.once(event, listener) Nu mun bt s kin v lin kt ti server, bn s dng:

1 2 3

server.once(connection, function (stream) { console.log(Ah, we have our first user!); }); emitter.removeListeners(event, listener) G b mt listener t mng listener m c t cho s kin. var callback = function(stream) { console.log(someone connected!); }; server.on(connection, callback); // ... server.removeListener(connection, callback); emitter.removeAllListener([event]) Nu bn cn, bn c th g b vic bt s kin t Event Emitter bi mt li gi n gin server.removeAllListeners(connection);

25

To mt Event Emitter
1 2 3 4 5 6 7 8 9 10

var EventEmitter = require(events).EventEmitter, util = require(util); // Here is the MyClass Contructor var MyClass = function(option1, option2) { this.option1 = option1; this.option2 = option2; } util.inherits(MyClass, EventEmitter); Trong trng hp ca ny, MyClass c th sinh ra cc s kin: MyClass.prototype.someMethod = function() { this.emit(custom event, some arguments); } var myInstance = new myClass(1, 2); myInstance.on(custom event, function() { console.log(got a custom event!); });

1 2 3

1 2 3 4

3.3.4

Buffer

Buffer l i tng c bn quan trng nht trong NodeJS. Khi truyn d liu qua mng, d liu c x l di dng nh phn. Tuy nhin, trong ngn ng Javascript mc nh khng c kiu d liu ny. NodeJS thm kiu d liu ny. Khi d liu gi n, mc nh l d liu nh phn. c th chuyn sang d liu vn bn, cn thit lp kiu m ha ca vn bn. V d nu vn bn m ha utf8, ta cn phi xc nh kiu m ha: buf.setEncoding(utf8); khi to mt Buffer t xu, ta lm nh sau: buf = new Buffer(str: string, [encoding]); V d ta mun to Buffer biu din xu "hello world" :
1

var buf = new Buffer("hello world"); Trn kiu Buffer ta c mt s phng thc sau: write(string: string, [offset: Number], [length: Number], [encoding: string]): ghi d liu vo xu.

26

1 2 3

buf = new Buffer(256); len = buf.write(\u00bd + \u00bc = \u00be, 0); console.log(len + " bytes: " + buf.toString(utf8, 0, len)); toString([encoding],[start], [end]): Tr v xu biu din Buffer tng ng. toJSON(): tr v i tng JSON. var buf = new Buffer(test); var json = JSON.stringify(buf); console.log(json); // [116,101,115,116] var copy = new Buffer(JSON.parse(json)); console.log(copy); // <Buffer 74 65 73 74> byteLength(string: string, [encoding]): tr v di xu // example byteLength method str = \u00bd + \u00bc = \u00be; console.log(str + ": " + str.length + "characters, " + Buffer.byteLength(str, utf8) + " bytes"); concat(list: array, [totalLength: Number]): Ni cc buffer vo buffer c. slice([start:Number],[end: Number]): Tr v mt Buffer mi. Buffer ny tham chiu n cng vng nh vi Buffer c nhng b gii han bi ch s start v end. var buf1 = new Buffer(26); for (var i = 0 ; i < 26 ; i++) { buf1[i] = i + 97; // 97 is ASCII a } var buf2 = buf1.slice(0, 3); console.log(buf2.toString(ascii, 0, buf2.length)); buf1[0] = 33; console.log(buf2.toString(ascii, 0, buf2.length)); fill(value: Number,[offset: Number],[end: Number]): in y Buffer vi d liu value.

1 2 3 4 5 6 7 8 9 10

1 2 3 4 5

1 2 3 4 5 6 7 8 9 10

27

1 2

var b = new Buffer(50); b.fill("h");

28

Chng 4 V d minh ha vi NodeJS


Trong phn ny, ta hy cng tm hiu mt ng dng chat n gin. M ngun ca chng trnh c th tm thy ti a ch: http://github.com/ Cu trc chng trnh c th hin qua hnh di y:

Tn file/Th mc Client client/server.js Server/ Server/server.js server/log.js server/startServer.js test/server/test.js

Miu t Th mc hin th ngi dng Qun l giao tip gia client v server Cha m ngun server Module Server Module log: qun l thng bo, ghi chp To mt th hin ca server v chy Test

29

4.1

Module Server

y l module chnh ca chng trnh.Nhim v ca n l khi to mt server lng nghe v phn hi cc kt ni. Trong v d ny, thc hin kt ni gia server v client, ta s s dng WebSocket mt cng ngh mi cho php to cc lung socket trn nn HTTP. Do vy tta phi khi to mt TCP Server:
1 2 3 4

this.server = tcp.createServer(function(socket){ }); server.listen(7000); c th qun l cc kt ni t client, ta to mt mng lu tr li cc kt ni.

1 2 3 4 5 6 7 8 9 10 11 12

this.connections = [] ... var self = this; this.server = tcp.createServer(function(socket){ var connection = new module.Connection(self, socket); self.addConnection(connection); }); this.addConnection = function(connection){ self.connctions.push(connection); connection.id = self.nextIdAssign++; } Khi c mt yu cu t pha client gi n, ta s gi broadcast cc tin nhn ti cc user khc:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

//gui tin nhan tu client this.say = function(){ self.broadcast(function(conn){ return [said, { is self: (conn.id == connection.id), message: message, nick: connection.nick } }); }; //broad cast this.broadcast = function(fn){ self.connection.each(function(connection){ var data = fn(connection); connection.send(data); } } 30

Khi client gi yu cu hy kt ni, ta phi loi b kt ni ca client ra khi danh sch kt ni: this.removeConnection = function(connection){ self.connection.remove(connection); log.debug(Connection: + self.connections.length); } By gi ta cng xt n lp kt ni. Mc ch lp ny qun l kt ni. Mt th hin ca lp ny cn lu tr thng tin server qun l n, socket, id v nick ang kt ni ti. Id ny do lp Server nh s. Trc ht n c dng gi li tin nhn do server nhn c trn. Ngoi ra trong v d ny, ta s cho php ngi dng ng k tn s dng. tin cho vic ny, ta vit thm phng thc qun l yu cu. Ta s qun l 2 loi yu cu: ng k nick Gi nhn tin nhn
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

1 2 3 4

this.Connection.prototype.handlers = { assignNick: function(connection, data) { log.debug(connection.logFormat(Assigning nick: + data)); connection.nick = data; connection.send([lastMessage, connection.server.lastNMessages(5)]); connection.server.broadcast(function(conn) { return [status, { nick: connection.nick, status: on }]; }) }, say: function(connection, data) { connection.server.say(connection, data); } };

4.2

Module Client

thc hin kt ni vi server ta s s dng WebSocket to mt socket yu cu ti server: . frame NodeJSChat.ws = new WebSocket(ws://localhost:7000) NodeJSChat.ws.onmessage = NodeJSChat.onmessage; NodeJSChat.ws.onclose = NodeJSChat.onclose; NodeJSChat.ws.onopen = NodeJSChat.onopen; T ta s xy dng cc hm callback tng ng vi tng s kin:

31

1 2 3 4 5 6 7 8 9

, onclose: function() { NodeJsChat.debug(socket closed); if (!NodeJsChat.windowClosing) { alert(Whoops! Looks like you lost internet connection or the server went down); } }, onmessage: function(evt) { var jsonData = JSON.parse(evt.data); var action var data = jsonData[0]; = jsonData[1];

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

if (NodeJsChat.handlers[action]) { NodeJsChat.handlers[action](data); } else { // This should be in a separate function. $(#messages).append(<tr><td cospan="2">Whoops, bad message from the server</td></tr>); } }, onopen: function() { NodeJsChat.debug(Connected...); NodeJsChat.send([ assignNick, NodeJsChat.nick ]); }, Khi ngi dng nhn gi tin, ta s s dng socket ny gi ti server:

1 2 3 4 5 6 7 8 9

say: function(message) { NodeJsChat.send([ say, return false; },

message ]);

send: function(data) { var dataStr = JSON.stringify(data); NodeJsChat.ws.send(dataStr); }, Cui cng, ta xy dng mt phng thc iu khin chung cho mi yu cu t client.Cc yu cu gm c: Cp nht cc tin nhn gn nht. Ghi nhn trng thi hin ti. 32

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

said: function(data) { var message = <div class="message">; var prefix = ; var tdClass = ; if (data.isSelf) { prefix = You:; tdClass = me; } else { prefix = data.nick + :; tdClass = nick; } message += <div class=" + tdClass + ">; message += prefix message += </div>; message message message message += <div class="message">; += data.message; += </div>; += </div>;

$(#messages).append(message); }, status: function(data) { var nick = data.nick; var stat = data[status]; var message = <div class="status"> + nick + just logged + stat + </div>; $(#messages).append(message); } };

33

Ti liu tham kho


1. The C10K problem: http://www.kegel.com/c10k.html 2. Trang web chnh thc ca NodeJS : http://nodejs.org/ 3. Mastering NodeJS: http://visionmedia.github.com/masteringnode/ 4. Biu lp cc lp chnh ca NodeJs: http://github.com/TuanZendF/NodeJS/uml/

34

You might also like