Está en la página 1de 23

Chng 6

Lp trnh Socket cho giao thc TCP


1. M hnh client/server
M hnh c ph bin nht v c chp nhn rng ri trong cc h thng phn tn l m hnh client/server. Trong m hnh ny s c mt tp cc tin trnh m mi tin trnh ng vai tr nh l mt trnh qun l ti nguyn cho mt tp hp cc ti nguyn cho trc v mt tp hp cc tin trnh client trong mi tin trnh thc hin mt tc v no cn truy xut ti ti nguyn phn cng hoc phn mm dng chung. Bn thn cc trnh qun l ti nguyn cn phi truy xut ti cc ti nguyn dng chung c qun l bi mt tin trnh khc, v vy mt s tin trnh va l tin trnh client va l tin trnh server. Cc tin trnh pht ra cc yu cu ti cc server bt k khi no chng cn truy xut ti mt trong cc ti nguyn ca cc server. Nu yu cu l ng n th server s thc hin hnh ng c yu cu v gi mt p ng tr li ti tin trnh client. M hnh client/server cung cp mt cch tip cn tng qut chia s ti nguyn trong cc h thng phn tn. M hnh ny c th c ci t bng rt nhiu mi trng phn cng v phn mm khc nhau. Cc my tnh c s dng chy cc tin trnh client/server c nhiu kiu khc nhau v khng cn thit phi phn bit gia chng; c tin trnh client v tin trnh server u c th chy trn cng mt my tnh. Mt tin trnh server c th s dng dch v ca mt server khc. M hnh truyn tin client/server hng ti vic cung cp dch v. Qu trnh trao i d liu bao gm: 1. Truyn mt yu cu t tin trnh client ti tin trnh server 2. Yu cu c server x l 3. Truyn p ng cho client M hnh truyn tin ny lin quan n vic truyn hai thng ip v mt dng ng b ha c th gia client v server. Tin trnh server phi nhn thc c thng ip c yu cu bc mt ngay khi n n v hnh ng pht ra yu cu trong client phi c tm dng (b phong ta) v buc tin trnh client trng thi ch cho t khi n nhn c p ng do server gi v bc ba. M hnh client/server thng c ci t da trn cc thao tc c bn l gi (send) v nhn (receive).

119

Client Server

Request message

Wait

Reply Execution

Request message

Tin trnh ang x l

Tin trnh ang phong ta


Hnh 4.1 Qu trnh giao tip client v server c th din ra theo mt t rong hai ch : b phong ta (blocked) v khng b phong ta (non-blocked). Ch b phong ta (blocked): Trong ch b phong ta, khi tin trnh client hoc server pht ra lnh gi d liu (send), vic thc thi ca tin trnh s b tm ngng cho ti khi tin trnh nhn pht ra lnh nhn d liu (receive). Tng t i vi tin trnh nhn d liu, nu tin trnh no (client hoc server) pht ra lnh nhn d liu, m ti thi im cha c d liu gi ti th vic thc thi ca tin trnh cng s b tm ngng cho ti khi c d liu gi ti. Ch khng b phong ta (non-blocked) Trong ch ny, khi tin trnh client hay server pht ra lnh gi d liu thc s, vic thc thi ca tin trnh vn c tin hnh m khng quan tm n vic c tin trnh no pht ra lnh nhn d liu hay khng. Tng t cho trng hp nhn d liu, khi tin trnh pht ra lnh nhn d liu, n s nhn d liu hin c, vic thc thi ca tin trnh vn c tin hnh m khng quan tm n vic c tin trnh no pht ra lnh gi d liu tip theo hay khng.

2. Cc kin trc Client/Server


2.1. Client/Server hai tng (two-tier client/server) Kin trc client/server n gin nht l kin trc hai tng. Trong thc t hu ht cc kin trc client/server l kin trc hai tng. Mt ng dng hai tng cung cp nhiu trm lm vic vi mt tng trnh din thng nht, tng ny truyn tin vi tng lu tr d liu tp trung. Tng trnh din thng thng l client, v tng lu tr d liu l server. Hu ht cc ng dng Internet nh l email, telnet, ftp thm ch l c Web l cc ng dng hai tng. Phn ln cc lp trnh vin trnh ng dng vit cc ng dng client/server c xu th s dng kin trc ny.

120

Trong ng dng hai tng truyn thng, khi lng cng vic x l c dnh cho pha client trong khi server ch n gin ng vai tr nh l chng trnh kim sot lung vo ra gia ng dng v d liu. Kt qu l khng ch hiu nng ca ng dng b gim i do ti nguyn hn ch ca PC, m khi lng d liu truyn i trn mng cng tng theo. Khi ton b ng dng c x l trn mt PC, ng dng bt buc phi yu cu nhiu d liu trc khi a ra bt k kt qu x l no cho ngi dng. Nhiu yu cu d liu cng lm gim hiu nng ca mng. Mt vn thng gp khc i vi ng dng hai tng l vn bo tr. Ch cn mt thay i nh i vi ng dng cng cn phi thay i li ton b ng dng client v server.

Hnh 4.2 2.2. Client/Server ba tng Ta c th trnh c cc vn ca kin trc client/server hai tng bng cch m rng kin trc thnh ba tng. Mt kin trc ba tng c thm mt tng mi tc bit vic x l d liu v tr trung tm.

Hnh 4.3

121

Theo kin trc ba tng, mt ng dng c chia thnh ba tng tch bit nhau v mt logic. Tng u tin l tng trnh din thng bao gm cc giao din ha. Tng th hai, cn c gi l tng trung gian hay tng tc nghip. Tng th ba cha d liu cn cho ng dng. Tng th ba v c bn l chng trnh thc hin cc li gi hm tm kim d liu cn thit. Tng trnh din nhn d liu v nh dng n hin th. S tch bit gia chc nng x l vi giao din to nn s linh hot cho vic thit k ng dng. Nhiu giao din ngi dng c xy dng v trin khai m khng lm thay i logic ng dng. Tng th ba cha d liu cn thit cho ng dng. D liu ny c th bao gm bt k ngun thng tin no, bao gm c s d liu nh Oracale, SQL Server hoc ti liu XML. 2.3. Kin trc n-tng Kin trc n-tng c chia thnh cc tng nh sau: Tng giao din ngi dng: qun l tng tc ca ngi dng vi ng dng Tng logic trnh din: Xc nh cch thc hin th giao din ngi dng v cc yu cu ca ngi dng c qun l nh th no. Tng logic tc nghip: M hnh ha cc quy tc tc nghip, Tng cc dch v h tng: Cung cp mt chc nng b tr cn thit cho ng dng nh cc thnh phn (truyn thng ip, h tr giao tc).

3. M hnh truyn tin socket


Server Socket() 1 Client Socket()

Bind()

Bind()

Listen()

3 4 Connect()

Accept()

Cc chc nng gi v nhn

Cc chc nng gi v nhn

Close()

Close()

Hnh 4.4

122

Khi lp trnh, ta cn quan tm n ch b phong ta, v n c th dn n tnh hung mt tin trnh no s ri vo vng lp v hn ca qu trnh gi hoc nhn. Trong chng 1 chng ta bit hai giao thc TCP v UDP l cc giao thc tng giao vn truyn d liu. Mi giao thc c nhng u v nhc im ring. Chng hn, giao thc TCP c tin cy truyn tin cao, nhng tc truyn tin b hn ch do phi c giai on thit lp v gii phng lin kt khi truyn tin, khi gi tin c li hay b tht lc th giao thc TCP phi c trch nhim truyn li,Ngc li, giao thc UDP c tc truyn tin rt nhanh v n ch c mt c ch truyn tin rt n gin: khng cn phi thit lp v gii phng lin kt. Khi lp trnh cho TCP ta s dng cc socket lung, cn i vi giao thc UDP ta s s dng lp DatagramSocket v DatagramPacket. Truyn tin hng lin kt ngha l cn c giai on thit lp lin kt v gii phng lin kt trc khi truyn tin. D liu c truyn trn mng Internet di dng cc gi (packet) c kch thc hu hn c gi l datagram. Mi datagram cha mt header v mt payload. Header cha a ch v cng cn truyn gi tin n, cng nh a ch v cng xut pht ca gi tin, v cc thng tin khc c s dng m bo tin cy truyn tin, payload cha d liu. Tuy nhin do cc datagram c chiu di hu hn nn thng phi phn chia d liu thnh nhiu gi v khi phc li d liu ban u t cc gi ni nhn. Trong qu trnh truyn tin c th c th c mt hay nhiu gi b mt hay b hng v cn phi truyn li hoc cc gi tin n khng theo ng trnh t. trnh nhng iu ny, vic phn chia d liu thnh cc gi, to cc header, phn tch header ca cc gi n, qun l danh sch cc gi nhn c v cc gi cha nhn c, ... rt nhiu cng vic cn phi thc hin, v i hi rt nhiu phn mm phc tp. Tht may mn, ta khng cn phi t thc hin cng vic ny. Socket l mt cuc cch mng ca Berkeley UNIX. Chng cho php ngi lp trnh xem mt lin kt mng nh l mt lung m c th c d liu ra hay ghi d liu vo t lung ny. V mt lch s Socket l mt s m rng ca mt trong nhng tng quan trng nht ca UNIX: tt c cc thao tc vo/ra ging nh vo ra tp tin i vi ngi lp trnh, cho d ta ang lm vic vi bn phm, mn hnh ha, mt file thng thng, hay mt lin kt mng. Cc Socket che du ngi lp trnh khi cc chi tit mc thp ca mng nh mi kiu ng truyn, cc kch thc gi, yu cu truyn li gi, cc a ch mng... Mt socket c th thc hin by thao tc c bn: Kt ni vi mt my xa (v d, chun b gi v nhn d liu) Gi d liu Nhn d liu Ngt lin kt Gn cng Nghe d liu n Chp nhn lin kt t cc my xa trn cng c gn

Lp Socket ca Java c s dng bi c client v server, c cc phng thc tng ng vi bn thao tc u tin. Ba thao tc cui ch cn cho server ch cc client lin kt vi chng. Cc thao tc ny c ci t bi lp ServerSocket. Cc socket cho client thng c s dng theo m hnh sau: Mt socket mi c to ra bng cch s dng hm Socket(). Socket c gng lin kt vi mt host xa. Mi khi lin kt c thit lp, cc host xa nhn cc lung vo v lung ra t socket, v s dng cc lung ny gi d liu cho nhau. Kiu lin kt ny c gi

123

l song cng (full-duplex)-cc host c th nhn v gi d liu ng thi. ngha ca d liu ph thuc vo giao thc. Khi vic truyn d liu hon thnh, mt hoc c hai pha ngt lin kt. Mt s giao thc, nh HTTP, i hi mi lin kt phi b ng sau mi khi yu cu c phc v. Cc giao thc khc, chng hn FTP, cho php nhiu yu cu c x l trong mt lin kt n.

4. Socket cho Client 4.1. Cc constructor public Socket(String host, int port) throws UnknownHostException, IOException Hm ny to mt socket TCP vi host v cng xc nh, v thc hin lin kt vi host xa. V d: try{ Socket s = new Socket( www.vnn.vn,80); } catch(UnknownHostException e){ System.err.println(e); } catch(IOException e){ System.err.println(e); } Trong hm ny tham s host l hostname kiu String, nu host khng xc nh hoc my ch tn min khng hot ng th constructor a ra ngoi l UnknownHostException. V mt l do no m khng th m c socket th constructor s a ra ngoi l IOException. C nhiu nguyn nhn khin cho mt lin kt tht bi: host m ta ang c gng kt ni ti khng chp nhn lin kt, kt ni Internet c th b ngt, hoc vn nh tuyn c th ngn nga cc gi tin ca ta ti ch. V d: Vit chng trnh kim tra trn 1024 cng u tin nhng cng no ang c server hot ng import java.net.*; import java.io.*; class PortScanner { public static void main(String[] args) { String host="localhost"; if(args.length>0){ host=args[0]; } for(int i=0;i<1024;i++){ try{ Socket s=new Socket(host,i); System.out.println("Co mot server dang hoat dong tren cong:"+i);

124

} catch(UnknownHostException e){ System.err.println(e); } catch(IOException e){ System.err.println(e); } } } } public Socket(InetAddress host, int port)throws IOException Tng t nh constructor trc, constructor ny to mt socket TCP vi thng tin l a ch ca mt host c xc nh bi mt i tng InetAddres v s hiu cng port, sau n thc hin kt ni ti host. N a ra ngoi l IOException nhng khng a ra ngoi l UnknownHostException. Constructor a ra ngoi l trong trng hp khng kt ni c ti host. public Socket (String host, int port, InetAddress interface, int localPort) throws IOException, UnknownHostException Constructor ny to ra mt socket vi thng tin l a ch IP c biu din bi mt i tng String v mt s hiu cng v thc hin kt ni ti host . Socket kt ni ti host xa thng qua mt giao tip mng v s hiu cng cc b c xc nh bi hai tham s sau. Nu localPort bng 0 th Java s la chn mt cng ngu nhin c sn nm trong khong t 1024 n 65535. public Socket (InetAddress host, int port, InetAddress interface, int localPort) throws IOException, UnknownHostException Constructor ch khc constructor trn ch a ch ca host lc ny c biu din bi mt i tng InetAddress. 4.2. Nhn cc thng tin v Socket i tng Socket c mt s trng thng tin ring m ta c th truy nhp ti chng thng qua cc phng thc tr v cc thng tin ny. public InetAddress getInetAddress() Cho trc mt i tng Socket, phng thc getInetAddress() cho ta bit host xa m Socket kt ni ti, hoc lin kt b ngt th n cho bit host xa m Socket kt ni ti public int getPort() Phng thc ny cho bit s hiu cng m Socket kt ni ti trn host xa. public int getLocalPort() Thng thng mt lin kt thng c hai u: host xa v host cc b. tm ra s hiu cng pha host cc b ta gi phng thc getLocalPort(). public InetAddress getLocalAddress() Phng thc ny cho ta bit giao tip mng no m mt socket gn kt vi n. public InputStream getInputStream() throws IOException

125

Phng thc geInputStream() tr v mt lung nhp c d liu t mt socket vo chng trnh. Thng thng ta c th gn kt lung nhp th InputStream ti mt lung lc hoc mt lung k t nhm a cc chc nng tin ch (chng hn nh cc lung InputStream, hoc InputStreamReader). tng cao hiu nng, ta c th m d liu bng cch gn kt n vi lung lc BufferedInputStream hoc BufferedReader. public OutputStream getOutputStream() throws IOException Phng thc getOutputStream() tr v mt lung xut th ghi d liu t ng dng ra u cui ca mt socket. Thng thng, ta s gn kt lung ny vi mt lung tin li hn nh lp DataOuputStream hoc OutputStreamWriter trc khi s dng n. tng hiu qu ghi. Hai phng thc getInputStream() v getOutputStream() l cc phng thc cho php ta ly v cc lung d liu nhp v xut. Nh cp chng 3 vo ra trong Java c tin hnh thng qua cc lung, vic lm vic vi cc socket cng khng phi l mt ngoi l. nhn d liu t mt my xa ta nhn v mt lung nhp t socket v c d liu t lung . ghi d liu ln mt my xa ta nhn v mt lung xut t socket v ghi d liu ln lung. Di y l hnh v ta hnh dung trc quan hn.

OutputStream

Chng trnh InputStream


Hnh 4.5 4.3. ng Socket

Socket

n thi im ta c y cc thng tin cn thit trin khai mt ng dng pha client. Khi vit mt chng trnh ng dng pha client tt c mi cng vic u chuyn v vic qun l lung v chuyn i d liu t lung thnh dng thc m ngi s dng c th hiu c. Bn thn cc socket rt n gin bi v cc phn vic phc tp c che du i. y chnh l l do socket tr thnh mt la chn c tnh chin lc cho lp trnh mng. public void close() throws IOException Cc socket c ng mt cch t ng khi mt trong hai lung ng li, hoc khi chng trnh kt thc, hoc khi socket c thu hi bi gabbage collector. Tuy nhin, thc t cho thy vic cho rng h thng s t ng socket l khng tt, c bit l khi cc chng trnh chy trong khong thi gian v hn. ng mt socket ta c th dng phng thc close(). Mi khi mt Socket b ng li, ta vn c th truy xut ti cc trng thng tin InetAddress, a ch cc b, v s hiu cng cc b thng qua cc phong thc getInetAddress(), getPort(), getLocalHost(), v getLocalPort(). Tuy nhin khi ta gi cc phng thc getInputStream() hoc getOutputStream() c d liu t lung c InputStream hoc ghi d liu OuputStream th ngoi l IOException c a ra.

126

Cc socket ng mt na (Half-closed socket) Phng thc close() ng c cc lung nhp v lung xut t socket. Trong mt s trng hp ta ch mun ng mt na kt ni, hoc l lung nhp hoc l lung xut. Bt u t Java 1.3, cc phng thc shutdownInput() v shutdownOutput() cho php ta thc hin iu ny. public void shutdownInput() throws IOException public void shutdownOutput() throws IOException

Cc phng thc ny khng thc s ngt lin kt. Tuy nhin, n ch iu chnh lung kt ni ti n sao cho. Trong Java 1.4 a thm vo hai phng thc cc lung nhp v lung xut m hay ng public boolean isInputShutdown() public boolean isOutputShutdown()

4.4. Thit lp cc ty chn cho Socket 4.4.1. TCP_NODELAY public void setTcpNoDelay(boolean on) throws SocketException public boolean getTcpNoDelay() throws SocketException Thit lp gi tr TCP_NODELAY l true m bo rng cc gi tin c gi i nhanh nht c th m khng quan tm n kch thc ca chng. Thng thng, cc gi tin nh c kt hp li thnh cc gi tin ln hn trc khi c gi i. Trc khi gi i mt gi tin khc, host cc b i nhn cc xc thc ca gi tin trc t h thng xa. 4.4.2. SO_LINGER public void setSoLinger(boolean on, int seconds) throws SocketException public int getSoLinger() throws SocketException Ty chn SO_LINGER xc nh phi thc hin cng vic g vi datagram vn cha c gi i khi mt socket b ng li. ch mc nh, phng thc close() s c hiu lc ngay lp tc; nhng h thng vn c gng gi phn d liu cn li. Nu SO_LINGER c thit lp bng 0, cc gi tin cha c gi i b ph hy khi socket b ng li. Nu SO_LINGER ln hn 0, th phng thc close() phong ta ch cho d liu c gi i v nhn c xc thc t pha nhn. Khi ht thi gian qui nh, socket s b ng li v bt k phn d liu cn li s khng c gi i. 4.4.3. SO_TIMEOUT public void setSoTimeout(int milliseconds) throws SocketException public int getSoTimeout() throws SocketException Thng thng khi ta c d liu t m socket, li gi phng thc phong ta cho ti khi nhn s byte. Bng cch thit lp phng thc SO_TIMEOUT, ta s m bo rng li gi phng thc s khng phong ta trong khong thi gian qu s giy quy nh. 4.5. Cc phng thc ca lp Object Lp Socket np chng phng thc chun ca lp java.lang.Object, toString(). V cc socket l cc i tng tm thi v thng ch tn ti khi lin kt tn ti. public String toString() Phng thc toString() to ra mt xu k t nh sau: Socket[addr=www.oreilly.com/198.122.208.11,port=80,localport=50055] Phng thc ny thng hu ch cho vic g ri.

127

4.6. Cc ngoi l Socket Hu ht cc phng thc ca lp Socket c khai bo a ra ngoi l IOException, hoc lp con ca lp IOExcepton l lp SocketException. 4.7. Cc lp SocketAddress Lp SocketAddress bt u c t phin bn Java 1.4, biu din mt u cui ca lin kt. Lp SocketAddress l mt lp tru tng m khng c phng thc no ngoi construtor mc nh. Lp ny c th c s dng cho c cc socket TCP v socket khng phi l TCP. Cc lp con ca lp SocketAddress cung cp thng tin chi tit hn thch hp cho kiu socket. Trong thc t, ch h tr TCP/IP. Mc ch chnh ca lp SocketAddress l cung cp mt ni lu tr cc thng tin lin kt socket tm thi (nh a ch IP v s hiu cng) c th c s dng li to ra socket mi. public SocketAddress getRemoteSocketAddress() public SocketAddress getLocalSocketAddress() C hai phng thc ny tr v gi tr null nu socket vn cha kt ni ti.

5. Lp ServerSocket
Lp ServerSocket c mi th ta cn vit cc server bng Java. N c cc constructor to cc i tng ServerSocket mi, cc phng thc lng nghe cc lin kt trn mt cng xc nh, v cc phng thc tr v mt Socket khi lin kt c thit lp, v vy ta c th gi v nhn d liu. Vng i ca mt server 1. Mt ServerSocket mi c to ra trn mt cng xc nh bng cch s dng mt constructor ServerSocket. 2. ServerSocket lng nghe lin kt n trn cng bng cch s dng phng thc accept(). Phng thc accept() phong ta cho ti khi mt client thc hin mt lin kt, phng thc accept() tr v mt i tng Socket m lin kt gia client v server. 3. Ty thuc vo kiu server, hoc phng thc getInputStream(), getOutputStream() hoc c hai c gi nhn cc lung vo ra truyn tin vi client. 4. server v client tng tc theo mt giao thc tha thun sn cho ti khi ngt lin kt. 5. Server, client hoc c hai ngt lin kt 6. Server tr v bc hai v i lin kt tip theo. 5.1. Cc constructor public ServerSocket(int port) throws IOException, BindException Constructor ny to mt socket cho server trn cng xc nh. Nu port bng 0, h thng chn mt cng ngu nhin cho ta. Cng do h thng chn i khi c gi l cng v danh v ta khng bit s hiu cng. Vi cc server, cc cng v danh khng hu ch lm v cc client cn phi bit trc cng no m n ni ti (ging nh ngi gi in thoi ngoi vic xc nh cn gi cho ai cn phi bit s in thoi lin lc vi ngi ).

128

V d: to mt server socket cho cng 80 try{ ServerSocket httpd = new ServerSocket(80); } catch(IOException e) { System. err.println(e); } Constructor a ra ngoi l IOException nu ta khng th to v gn Socket cho cng c yu cu. Ngoi l IOException pht sinh khi: Cng c s dng Khng c quyn hoc c lin kt vi mt cng nm gia 0 v 1023. V d; import java.net.*; import java.io.*; public class congLocalHost { public static void main(String[] args) { ServerSocket ss; for(int i=0;i<=1024;i++) { try{ ss= new ServerSocket(i); ss.close(); } catch(IOException e) { System.out.println("Co mot server tren cong "+i); } } } } public ServerSocket(int port, int queuelength, InetAddress bindAddress)throws IOException

Constructor ny to mt i tng ServerSocket trn cng xc nh vi chiu di hng i xc nh. ServerSocket ch gn cho a ch IP cc b xc nh. Constructor ny hu ch cho cc server chy trn cc h thng c nhiu a ch IP.

129

5.2. Chp nhn v ngt lin kt Mt i tng ServerSocket hot ng trong mt vng lp chp nhn cc lin kt. Mi ln lp n gi phng thc accept(). Phng thc ny tr v mt i tng Socket biu din lin kt gia client v server. Tng tc gi client v server c tin hnh thng qua socket ny. Khi giao tc hon thnh, server gi phng thc close() ca i tng socket. Nu client ngt lin kt trong khi server vn ang hot ng, cc lung vo ra kt ni server vi client s a ra ngoi l InterruptedException trong ln lp tip theo public Socket accept() throws IOException Khi bc thit lp lin kt hon thnh, v ta sn sng chp nhn lin kt, cn gi phng thc accept() ca lp ServerSocket. Phng thc ny phong ta; n dng qu trnh x l v i cho ti khi client c kt ni. Khi client thc s kt ni, phng thc accept() tr v i tng Socket. Ta s dng cc phng thc getInputStream() v getOutputStream() truyn tin vi client. V d: try{ ServerSocket theServer = new ServerSocket(5776); while(true) { Socket con = theServer.accept(); PrintStream p = new PrintStream(con.getOutputStream()); p.println(Ban da ket noi toi server nay. Bye-bye now.); con.close(); } } catch(IOException e) { System.err.println(e); } public void close() throws IOException Nu ta kt thc lm vic vi mt i tng server socket th cn phi ng li i tng ny. V d: Ci t mt server daytime import java.net.*; import java.io.*; import java.util.Date; public class daytimeServer{ public final static int daytimePort =13; public static void main(String[]args) { ServerSocket theServer; Socket con;

130

PrintStream p; try{ theServer = new ServerSocket(daytimePort); try{ p= new PrintStream(con.getOutputStream()); p.println(new Date()); con.close(); } catch(IOException e) { theServer.close(); System. err.println(e); } } catch(IOException e) { System. err.println(e); } } } public void close() throws IOException Nu hon thnh cng vic vi mt ServerSocket, ta cn phi ng n li, c bit nu chng trnh ca ta tip tc chy. iu ny nhm to iu kin cho cc chng trnh khc mun s dng n. ng mt ServerSocket khng ng nht vi vic ng mt Socket. Lp ServerSocket cung cp mt s phng thc cho ta bit a ch cc b v cng m trn i tng server ang hot ng. Cc phng thc ny hu ch khi ta m mt i tng server socket trn mt cng v danh v trn mt giao tip mng khng public InetAddress getInetAddress() Phng thc ny tr v a ch c s dng bi server (localhost). Nu localhost c a ch IP, a ch ny c tr v bi phng thc InetAddress.getLocalHost() V d: try{ ServerSocket httpd = new ServerSocket(80); InetAddress ia = httpd.getInetAddress(); } catch(IOException { } public int getLocalHost() e)

131

Cc contructor ServerSocket cho php ta nghe d liu trn cng khng nh trc bng cch gn s 0 cho cng. Phng thc ny cho php ta tm ra cng m server ang nghe.

6. Cc bc ci t chng trnh pha Client bng Java


Sau khi tm hiu cc lp v cc phng thc cn thit ci t chng trnh Socket. mc 6 v mc 7 chng ta s i vo cc bc c th ci t cc chng trnh Client v Server. Cc bc ci t Client Bc 1:To mt i tng Socket Socket client =new Socket(hostname,portName); Bc 2:To mt lung xut c th s dng gi thng tin ti Socket PrintWriter out=new PrintWriter(client.getOutputStream(),true); Bc 3:To mt lung nhp c thng tin p ng t server BufferedReader(new BufferedReader in=new InputStreamReader(client.getInputStream()));

Bc 4:Thc hin cc thao tc vo/ra vi cc lung nhp v lung xut i vi cc lung xut, PrintWriter, ta s dng cc phng thc print v println, tng t nh System.out.println. i vi lung nhp, BufferedReader, ta c th s dng phng thc read() c mt k t, hoc mt mng cc k t, hoc gi phng thc readLine() c vo mt dng k t. Cn ch rng phng thc readLine() tr v null nu kt thc lung. Bc 5: ng socket khi hon thnh qu trnh truyn tin V d: Vit chng trnh client lin kt vi mt server. Ngi s dng nhp vo mt dng k t t bn phm v gi d liu cho server. import java.net.*; import java.io.*; public class EchoClient1 { public static void main(String[] args) { String hostname="localhost"; if(args.length>0) { hostname=args[0]; } PrintWriter pw=null; BufferedReader br=null; try{ Socket s=new Socket(hostname,2007);

br=new InputStreamReader(s.getInputStream()));

BufferedReader(new

132

BufferedReader InputStreamReader(System.in));

user=new

BufferedReader(new

pw=new PrintWriter(s.getOutputStream()); System.out.println("Da ket noi duoc voi server..."); while(true) { String st=user.readLine(); if(st.equals("exit")) { break; } pw.println(st); pw.flush(); System.out.println(br.readLine()); } } catch(IOException e) { System.err.println(e); } finally{ try{ if(br!=null)br.close(); if(pw!=null)pw.close(); } catch(IOException e) { System.err.println(e); } } } } Chng trnh EchoClient c vo hostname t i dng lnh. Tip theo ta to mt socket vi hostname xc nh trn cng s 2007. Tt nhin cng ny hon ton do ta la chn sao cho n khng trng vi cng c dch v hot ng. Vic to socket thnh cng c ngha l ta lin kt c vi server. Ta nhn lung nhp t socket thng qua phng thc getInputStream() v gn kt n vi cc lung k t v lung m nh lnh: br=new BufferedReader(new InputStreamReader(s.getInputStream()); Tng t ta ly v lung xut thng qua phng thc getOuputStream() ca socket. Sau gn kt lung ny vi lung PrintWriter gi d liu ti server

133

pw=new PrintWriter(s.getOutputStream()); c d liu t bn phm ta gn bn phm vi cc lung nhp nh cu lnh: BufferedReader user=new BufferedReader(new InputStreamReader(System.in)); Sau i to c cc lung th vn nhn v gi d liu tr thnh vn n gin l c d liu t cc lung nhp br, user v ghi d liu ln lung xut pw.

7. Cc bc ci t chng trnh Server bng Java


ci t chng trnh Server bng ServerSocket ta thc hin cc bc sau: Bc 1 To mt i tng ServerSocket ServerSocket ss=new ServerSocket(port) Bc 2: To mt i tng Socket bng cch chp nhn lin kt t yu cu lin kt ca client. Sau khi chp nhn lin kt, phng thc accept() tr v i tng Socket th hin lin kt gia Client v Server. while(condion) { Socket s=ss.accept(); doSomething(s); } Ngi ta khuyn co rng chng ta nn giao cng vic x l i tng s cho mt tuyn on no . Bc 3: To mt lung nhp c d liu t client BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream())); Bc 4: To mt lung xut gi d liu tr li cho server PrintWriter pw=new PrintWriter(s.getOutputStream(),true); Trong tham s true c s dng xc nh rng lung s c t ng y ra. Bc 5: Thc hin cc thao tc vo ra vi cc lung nhp v lung xut Bc 6: ng socket s khi truyn tin xong. Vic ng socket cng ng ngha vi vic ng cc lung.

V d: Vit chng trnh server EchoServer phc v chng trnh EchoClient1 vit bc 5 import java.net.*; import java.io.*; public class EchoServer1 { public final static int DEFAULT_PORT=2007; public static void main(String[] args) { int port=DEFAULT_PORT; try{ ServerSocket ss=new ServerSocket(port);

134

Socket s=null; while(true) { try{ s=ss.accept(); PrintWriter OutputStreamWriter(s.getOutputStream())); pw=new br=new PrintWriter(new BufferedReader(new

BufferedReader InputStreamReader(s.getInputStream())); while(true){ String line=br.readLine(); if(line.equals("exit"))break;

String upper=line.toUpperCase(); pw.println(upper); pw.flush(); } } catch(IOException e) { } finally{ try{ if(s!=null){ s.close(); } } catch(IOException e){} } } } catch(IOException e) { } } }

135

Chng trnh bt u bng vic to ra mt i tng ServerSocket trn cng xc nh. Server lng nghe cc lin kt trong mt vng lp v hn. N chp nhn lin kt bng cch gi phng thc accept(). Phng thc accept() tr v mt i tng Socket th hin mi lin kt gia client v server. Ta cng nhn v cc lung nhp v lung xut t i tng Socket nh cc phng thc getInputStream() v getOuputStream(). Vic nhn yu cu t client s thng qua cc lung nhp v vic gi p ng ti server s thng qua lung xut. Khi ng chng trnh server start java EchoServer1

Hnh 4.6 Khi ng client C:\MyJava>start java EchoClient1

Hnh 4.7

8. ng dng a tuyn on trong lp trnh Java


Cc server nh vit trn rt n gin nhng nhc im ca n l b hn ch v mt hiu nng v n ch qun l c mt client ti mt thi im. Khi khi lng cng vic m server cn x l mt yu cu ca client l qu ln v khng bit trc c thi im hon thnh cng vic x l th cc server ny l khng th chp nhn c. khc phc iu ny, ngi ta qun l mi phin ca client bng mt tuyn on ring, cho php cc server lm vic vi nhiu client ng thi. Server ny c gi l server tng tranh (concurrent server)-server to ra mt tuyn on qun l tng yu cu, sau tip tc lng nghe cc client khc. Chng trnh client/server chng ta xt m mc 6 v mc 7 l chng trnh client/server n tuyn on. Cc server n tuyn on ch qun l c mt lin kt ti mt thi im. Trong thc t mt server c th phi qun l nhiu lin kt cng mt lc. thc hin iu ny server chp nhn cc lin kt v chuyn cc lin kt ny cho tng tuyn on x l. Trong phn di y chng ta s xem xt cch tin hnh ci t mt chng trnh client/server a tuyn on. Chng trnh pha server import java.io.*; import java.net.*; class EchoServe extends Thread

136

{ private Socket socket; private BufferedReader in; private PrintWriter out; public EchoServe (Socket s) throws IOException { socket = s; System.out.println("Serving: "+socket); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); // Cho php auto-flush: out = new PrintWriter(new BufferedWriter(new OutputStreamWriter( socket.getOutputStream())), true); // Nu bt k li gi no trn a ra ngoi l // th chng trnh gi c trch nhim ng socket. Ngc li tuyn on s // s ng socket start(); } public void run() { try { while (true) { System.out.println("....Server is waiting..."); String str = in.readLine(); if (str.equals(exit) ) break; System.out.println("Received: " + str); System.out.println("From: "+ socket); String upper=str.toUpperCase(); // gi li cho client out.println(upper); } System.out.println("Disconnected with.."+socket); } catch (IOException e) {} finally { try {

137

socket.close(); } catch(IOException e) {} } } } public class TCPServer1 { static int PORT=0; . public static void main(String[] args) throws IOException { if (args.length == 1) { PORT=Integer.parseInt(args[0]); // Nhp s hiu cng t i dng lnh } // To mt i tng Server Socket ServerSocket s = new ServerSocket(PORT); InetAddress addrs= InetAddress.getLocalHost(); System.out.println("TCP/Server running on : "+ addrs +" ,Port "+s.getLocalPort()); try { while(true) { // Phong ta cho ti khi c mt lin kt n Socket socket = s.accept(); try { new EchoServe(socket); // To mt tuyn on qun l ring tng lin kt } catch(IOException e) { socket.close(); } } } finally { s.close();

138

} } } Chng trnh pha client import java.net.*; import java.io.*; public class TCPClient1 { public static void main(String[] args) throws IOException { if (args.length != 2) { System.out.println("S dng: java TCPClient hostid port#"); System.exit(0); } try { InetAddress addr = InetAddress.getByName(args[0]); Socket socket = new Socket(addr, Integer.parseInt(args[1])); try { System.out.println("socket = " + socket); BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); // Output is automatically flushed by PrintWriter: PrintWriter out =new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); // c dng k t t bn phm DataInputStream myinput = new DataInputStream(new BufferedInputStream(System.in)); try {

139

for(;;) { System.out.println("Type anything followed by RETURN, or Exit to terminate the program."); String strin=myinput.readLine(); // Quit if the user typed ctrl+D if (strin.equals("exit")) break; else out.println(strin); String strout = in.readLine(); { // Compare Both Strings System.out.println("Received: "+strout); } else System.out.println("Echo bad -- string unequal"+ strout); } // of for ;; } catch (IOException e) { e.printStackTrace(); } // User is exiting } finally { System.out.println("EOF...exit"); socket.close(); } } catch(UnknownHostException e) { System.err.println("Can't find host"); System.exit(1); } catch (SocketException e) // Send the message // Recive it back

if ( strin.length()==strout.length())

140

{ System.err.println("Can't open socket"); e.printStackTrace(); System.exit(1); } } }

9. Kt lun
Chng ta tm hiu cch lp trnh mng cho giao thc TCP. Cc Socket cn c gi l socket lung v gi v nhn d liu u c tin hnh thng qua vic c ghi cc lung. Ta c cng tm hiu c ch hot ng ca socket v cch thc lp cc chng trnh server v client. Ngoi ra, chng ny cng gii thch to sao cn c ci t server a tuyn on v tm hiu cch thc lp cc chng trnh client/server a tuyn on. Trong chng tip theo chng ta s hc cch xy dng mt chng trnh client/server cho giao thc UDP, mt giao thc gn vi giao thc TCP.

141