[Docx.vn] Xay Dung Chuong Trinh Chat Room Client-server Bang Socket Trong Java

Embed Size (px)

Citation preview

  • TRNG I HC BCH KHOA

    KHOA CNG NGH THNG TIN

    B MN MNG V TRUYN THNG

    N MN HC

    LP TRNH MNG MY TNH

    TI

    S dng Socket trong Java xy dng chng trnh CHAT

    Room theo m hnh Client-Server

    GVHD : TRN H THY TIN

    Sinh vin : Trn Anh Tun

    Lp : 06T3

    Nhm : 09B

    Nng 2011

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 2

    MC LC

    MC LC ............................................................................................................... 2

    DANH MC HNH ................................................................................................. 3

    TNG QUAN V TI ..................................................................................... 4 Chng 1. C S L THUYT .............................................................................................................. 5

    1.1. Giao thc TCP/IP ......................................................................................................................... 5 1.1.1. Giao thc IP(Internet Protocol - Giao thc Lin mng) ....................................................... 5 1.1.2. Giao thc TCP(Transmission Control Protocol - "Giao thc iu khin truyn vn") ......... 7

    1.2. M hnh Client/Server .................................................................................................................. 8 1.3. C ch Socket trong Java ........................................................................................................... 10

    1.3.1. Khi qut v Socket............................................................................................................ 10 1.3.2. C ch Socket..................................................................................................................... 10 1.3.3. M hnh truyn tin socket................................................................................................... 11 1.3.4. Mt s hm c bn trong socket ......................................................................................... 14

    Chng 2. THIT K V XY DNG H THNG ........................................................................... 17 2.1. Phn tch yu cu ........................................................................................................................ 17 2.2. Phn tch cc chc nng ............................................................................................................. 17 2.3. Thit k k chng trnh ............................................................................................................. 18

    2.3.1. Thit k giao din ............................................................................................................... 18 2.3.2. Xy dng cc chc nng .................................................................................................... 19

    Chng 3. TRIN KHAI V NH GI KT QU ........................................................................... 20 3.1. Mi trng trin khai ................................................................................................................. 20 3.2. Kt qu cc chc nng ca chng trnh .................................................................................... 20

    KT LUN V HNG PHT TRIN ............................................................. 23 1. NHNG KT QU T C .......................................................................... 23

    2. NHNG VN TN TI ................................................................................ 23

    3. HNG PHT TRIN ....................................................................................... 23

    PH LC .............................................................................................................. 24 1. CHNG TRNH SERVER: ............................................................................... 24

    1.1. Chatserver class: .................................................................................. 24

    1.2. serverSocket class: .............................................................................. 27

    2. CHNG TRNH CLIENT ................................................................................. 30

    2.1. Client class: ......................................................................................... 30

    2.2. ClientLogin class: ................................................................................ 38

    2.3. clientSocket ......................................................................................... 44

    TI LIU THAM KHO ..................................................................................... 49

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 3

    DANH MC HNH

    Hnh 1: S TCP/IP ............................................................................................ 5 Hnh 2 : Cu trc Header ca IP ............................................................................ 7 Hnh 3 : Cu trc header cua TCP ......................................................................... 8 Hnh 4 : M hnh client/server ............................................................................... 9

    Hnh 5 : Client gi yu cu kt ni ti Server ..................................................... 11 Hnh 6 : Server ng kt ni v tip tc lng nghe. ......................................... 11 Hnh 7 : M hnh truyn tin socket ..................................................................... 12 Hnh 8 : M hnh tng tc gia client/server qua socket TCP .......................... 13 Hnh 9 : V d v mt chng trnh socket TCP ............................................... 15 Hnh 10 : V d v mt chng trnh socket TCP .............................................. 16 Hnh 11: Giao din login .................................................................................... 18 Hnh 12: Giao din Chat room ............................................................................ 18 Hnh 13 : Kt ni li khi Server cha chy ........................................................ 20 Hnh 14 : Chy chng trnh server .................................................................... 20 Hnh 15 : Login thnh cng vo phng Chat....................................................... 21

    Hnh 16 : Th nghim Chat private ..................................................................... 22 Hnh 17 : Hin th thng bo login v logout trn Server ................................... 22

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 4

    TNG QUAN V TI

    1. Bi cnh v l do thc hin ti Ngy nay, nhu cu v cng ngh thng tin trong i sng l a dng.

    Vic m rng cc h thng truyn thng v ngy c nhiu my vi tnh kt ni vo mng Internet. Vi vic ng dng giao thc TCP/IP lm cho h thng mng ngy cng rng hn v pht trin vt bt. Vn an ninh, bo mt,l mt th mnh ca giao thc ny em li cho cng ngh truyn thng.

    Bn cnh vic pht trin ca th in t bng nhiu dch v khc nhau(gmail, yahoo,MSM trong mng in thoi di ng), vic CHAT trc tuyn v gi flie trc tip trn Internet cng l nhu cu khng th thiu.

    Vi thc t nh vy, nhm chng em nghin cu v xy dng m hnh CHAT v truyn file trong mng LAN.

    2. Phng php trin khai ti Ngn ng lp trnh : Java

    Chng trnh son tho v build : NetBeans IDE

    S dng Giao thc TCP/IP S dng Socket trong Java

    3. Kt cu ca n Gm ba chng: Chng 1: C s l thuyt Chng 2: Thit k v xy dng h thng Chng 3: Trin khai v nh gi kt qu

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 5

    Chng 1. C S L THUYT

    1.1. Giao thc TCP/IP TCP/IP l tn chung cho mt tp hp hn 100 giao thc c s dng

    kt ni cc my tnh vo mng, trong hai giao thc chnh l TCP (Transmission Control Protocol) v IP (Internet Protocol).

    Trong phm vi Internet, thng tin khng c truyn ti nh mt dng ring bit t my tnh ny ti my tnh khc. Thay vo , d liu c chia thnh nhng gi nh gi l packet.

    Cc packet ny c gi trn mng my tnh. Cng vic ca IP l chuyn chng n cc my tnh xa. Ti trm cui, TCP nhn cc packet v kim tra li. Nu mt li xut hin, TCP yu cu gi ring bit phi c gi li. Ch khi tt c cc packet nhn c l ng, TCP s s dng s th t to li thng tin ban u.

    Hnh 1: S TCP/IP

    1.1.1. Giao thc IP(Internet Protocol - Giao thc Lin mng)

    L mt giao thc hng d liu c s dng bi cc my ch ngun v ch truyn d liu trong mt lin mng chuyn mch gi.

    D liu trong mt lin mng IP c gi theo cc khi c gi l cc gi (packet hoc datagram). C th, IP khng cn thit lp cc ng truyn trc khi mt my ch gi cc gi tin cho mt my khc m trc n cha tng lin lc vi.

    Giao thc IP cung cp mt dch v gi d liu khng m bo (cn gi l c gng cao nht), ngha l n hu nh khng m bo g v gi d liu.

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 6

    Gi d liu c th n ni m khng cn nguyn vn, n c th n khng theo th t (so vi cc gi khc c gi gia hai my ngun v ch ), n c th b trng lp hoc b mt hon ton. Nu mt phn mm ng dng cn c bo m, n c th c cung cp t ni khc, thng t cc giao thc giao vn nm pha trn IP.

    Cc thit b nh tuyn lin mng chuyn tip cc gi tin IP qua cc mng tng lin kt d liu c kt ni vi nhau. Vic khng c m bo v gi d liu c ngha rng cc chuyn mch gi c thit k n gin hn. (Lu rng nu mng b gi tin, lm i th t hoc lm hng nhiu gi tin, ngi dng s thy hot ng mng tr nn km i. Hu ht cc thnh phn ca mng u c gng trnh xy ra tnh trng . l l do giao thc ny cn c gi l c gng cao nht. Tuy nhin, khi li xy ra khng thng xuyn s khng c hiu qu xu n mc ngi dng nhn thy c.)

    Giao thc IP rt thng dng trong mng Internet cng cng ngy nay. Giao thc tng mng thng dng nht ngy nay l IPv4; y l giao thc IP phin bn 4. IPv6 c ngh s k tip IPv4: Internet ang ht dn a ch IPv4, do IPv4 s dng 32 bit nh a ch (to c khong 4 t a ch); IPv6 dng a ch 128 bit, cung cp ti a khong 3.41038 a ch . Cc phin bn t 0 n 3 hoc b hn ch, hoc khng c s dng. Phin bn 5 c dng lm giao thc dng (stream) th nghim. Cn c cc phin bn khc, nhng chng thng dnh l cc giao thc th nghim v khng c s dng rng ri.

    a ch IP c chia thnh 4 s gii hn t 0 - 255. Mi s c lu bi 1 byte - > IP c kch thc l 4byte, c chia thnh cc lp a ch. C 3 lp l A, B, v C. Nu lp A, ta s c th c 16 triu i ch, lp B c 65536 a ch. V d: lp B chng ta c tt c cc a ch t 132.25.0.0 n 132.25.255.255. Phn ln cc a ch lp A l s hu ca cc cng ty hay ca t chc. Mt ISP thng s hu mt vi a ch lp B hoc C. V d: Nu a ch IP ca bn l 132.25.23.24 th bn c th xc nh ISP ca bn l ai. (c IP l 132.25.x.)

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 7

    Hnh 2 : Cu trc Header ca IP

    1.1.2. Giao thc TCP(Transmission Control Protocol - "Giao thc iu khin

    truyn vn")

    L mt trong cc giao thc ct li ca b giao thc TCP/IP. S dng TCP, cc ng dng trn cc my ch c ni mng c th to cc "kt ni" vi nhau, m qua chng c th trao i d liu hoc cc gi tin. Giao thc ny m bo chuyn giao d liu ti ni nhn mt cch ng tin cy v ng th t. TCP cn phn bit gia d liu ca nhiu ng dng (chng hn, dch v Web v dch v th in t) ng thi chy trn cng mt my ch.

    TCP h tr nhiu giao thc ng dng ph bin nht trn Internet v cc ng dng kt qu, trong c WWW, th in t v Secure Shell.

    Trong b giao thc TCP/IP, TCP l tng trung gian gia giao thc IP bn di v mt ng dng bn trn. Cc ng dng thng cn cc kt ni ng tin cy kiu ng ng lin lc vi nhau, trong khi , giao thc IP khng cung cp nhng dng kiu , m ch cung cp dch v chuyn gi tin khng ng tin cy. TCP lm nhim v ca tng giao vn trong m hnh OSI n gin ca cc mng my tnh.

    Cc ng dng gi cc dng gm cc byte 8-bit ti TCP chuyn qua mng. TCP phn chia dng byte ny thnh cc on (segment) c kch thc thch hp (thng c quyt nh da theo kch thc ca n v truyn dn ti a (MTU) ca tng lin kt d liu ca mng m my tnh ang nm trong ). Sau , TCP chuyn cc gi tin thu c ti giao thc IP gi n qua mt lin mng ti m un TCP ti my tnh ch. TCP kim tra m bo khng c gi tin no b tht lc bng cch gn cho mi gi tin mt "s th t" (sequence number). S th t ny cn c s dng m bo d liu c trao cho ng dng ch theo ng th t. M un TCP ti u kia gi li "tin

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 8

    bo nhn" (acknowledgement) cho cc gi tin nhn c thnh cng; mt "ng h" (timer) ti ni gi s bo time-out nu khng nhn c tin bo nhn trong khong thi gian bng mt round-trip time (RTT), v d liu (c coi l b tht lc) s c gi li. TCP s dng checksum (gi tr kim tra) xem c byte no b hng trong qu trnh truyn hay khng; gi tr ny c tnh ton cho mi khi d liu ti ni gi trc khi n c gi, v c kim tra ti ni nhn.

    Hnh 3 : Cu trc header cua TCP

    1.2. 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

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 9

    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)

    Hnh 4 : M hnh client/server

    Qu trnh giao tip client v server c th din ra theo mt trong 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

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 10

    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.

    1.3. C ch Socket trong Java

    1.3.1. Khi qut v Socket

    Nh chng ta bit kt ni URLs v URL cung cp cho chng ta mt c cu truy xut vo cc ti nguyn trn Internet mt mc tng i cao, nhng i khi chng trnh ca chng ta li yu cu mt giao tip tng mng mc thp.V d khi chng ta vit mt ng dng client-server.

    Trong mt ng dng client-server th pha server s cung cp mt s dch v, nh: x l c s d liu, cc yu cu bn pha client a ra, sau s gi li cho pha client. S giao tip nh vy gi l tin cy bi v d liu s khng b mt mt, sai lch trong qu trnh truyn, server gi cho client thng ip g th pha client s nhn c thng ip nguyn nh vy. Giao thc TCP s cung cp cho chng ta mt cch thc truyn tin cy. c th ni chuyn c trn TCP th chng trnh client v chng trnh server phi thip lp mt ng truyn, v mi chng trnh s phi kt ni li vi socket l im cui kt ni, client v server mun ni chuyn vi nhau th s phi thng qua socket, mi thng ip s phi i qua socket. Chng ta c mng tng socket y l mt ci ca mi ngi mun i ra hay i vo u phi thng qua ci ca ny.

    1.3.2. C ch Socket

    Mt socket l mt im cui ca thng tin hai chiu lin kt gia hai chng trnh ang chy trn mng. Nhng lp socket c dng i din cho kt ni gia mt chng trnh client v mt chng trnh server. Trong Java gi Java.net cung cp hai lp Socket v ServerSocket thc hin kt ni gia client v server.

    Thng thng th server s chy trn mt my c bit v c mt socket gii hn trong 1 Portnumber c bit.

    Pha client: client c bit hostname ca my m server ang chy v port number m server ang lng nghe. to mt yu cu kt ni client s

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 11

    th hn gp server trn my ca server thng qua port number. Client cng cn xc nh chnh n vi server thng qua local port number.

    Hnh 5 : Client gi yu cu kt ni ti Server

    Nu mi th tt p th server s ng kt ni. khi ng kt ni th server s to ra mt socket mi ni chuyn vi client v cng to ra mt socket khc tip tc lng nghe.

    Hnh 6 : Server ng kt ni v tip tc lng nghe.

    1.3.3. M hnh truyn tin socket

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 12

    Hnh 7 : M hnh truyn tin socket

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 13

    Hnh 8 : M hnh tng tc gia client/server qua socket TCP

    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.

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 14

    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 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.

    1.3.4. Mt s hm c bn trong socket

    Class m t v socket - To mt socket Socket(InetAddress address, int port)

    Socket(String host, int port)

    Socket(InetAddress address, int port, InetAddress, localAddr, int

    localPort)

    Socket(String host, int port, InetAddress, localAddr, int localPort)

    Socket()

    - Ly thng tin v mt socket InetAddress getInetAddress() : tr v a ch m socket kt ni n int getPort() : tr v a ch m socket kt ni n. InetAddress getLocalAddress() : tr v a ch cc b. int getLocalPort() : tr v a ch cc b. - S dng Streams public OutputStream getOutputStream() throws IOException: Tr v

    mt output stream cho vic vit cc byte n socket ny. public InputStream getInputStream() throws IOException : Tr v

    mt input stream cho vic c cc byte t socket ny. ServerSocket class

    - Class m t ServerSocket To mt ServerSocket ServerSocket(intport) throws IOException ServerSocket(intport,

    intbacklog) throws IOException ServerSocket(intport, intbacklog,

    InetAddressbindAddr) throws IOException

    - Cc phng thc trong ServerSocket Socket accept() throws IOException: lng nghe mt kt ni n socket

    ny v c chp nhn n hay khng void close() throws IOException: ngsocket.

    InetAddress getInetAddress() : tr v a ch cc b ca socket int getLocalPort() : tr v port m server ang lng nghe

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 15

    Hnh 9 : V d v mt chng trnh socket TCP

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 16

    Hnh 10 : V d v mt chng trnh socket TCP

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 17

    Chng 2. THIT K V XY DNG H

    THNG

    2.1. Phn tch yu cu - Yu cu ca bi ton: Xy dng m hnh Client Server ng dng

    CHAT

    - Xy dng chng trnh Server To mt TCP Socket v gn vo mt cng Xy dng mt chng trnh Server a tuyn (Threaded Server) cho

    php nhiu Client kt ni ti Server.Mi tuyn m nhn lin lc vi Client. Ch v lng nghe yu cu kt ni t Client Chp nhn kt ni v nhn Socket tng ng. Truyn nhn thng tin qua cc lung nhn/gi d liu ca socket. Khi mt user login vo Server th Server s cp nht user v gi ti

    cc Client ang kt ni Khi mt user logout ra khi Server th Server hin thng bo user

    logout v gi ti Client. ng kt ni. - Xy dng chng trnh Client. To mt TCP Socket vi a ch IP v s cng m chng trnh Server

    ang chy Thit lp kt ni ti Server Trao i d liu vi Server. Cp nht cc user khc va logint/logout. Gi/ nhn thng ip ti tt c mi ngi c trong phng cht ng kt ni Thit k giao din hin th khung chat pha Client. - S dng giao thc TCP/IP - Yu cu giao din: Vng thao tc chui(CHAT): CHAT trc tip gia Client v Server khi c kt ni. Trao i d liu vi nhau nh vo Stream nhp v Stream xut.

    2.2. Phn tch cc chc nng Chc nng ca chng trnh c th hin qua chng trnh Client v

    Server.

    Chc nng Chat trong mng LAN: Chui k t nhp t bn phm. n nt Send gi chui k t va nhp giao tip vi nhau gia

    Client v Server.

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 18

    Xy dng chng trnh Client: ni kt n Server trong mng trao i thng tin v truyn ti d liu.

    Xy dng chng trnh Server a tuyn kt ni vi nhiu Client: X l cc yu cu ni kt: lng nghe yu cu ni kt ca Client. X l cc thng ip yu cu t Client: chp nhn hoc t chi ni kt.

    2.3. Thit k k chng trnh

    2.3.1. Thit k giao din

    Hnh 11: Giao din login

    Hnh 12: Giao din Chat room

    Server ip/host name: a ch ip hay hostname ca Server (mc nh l a ch localhost).

    Port : s hiu cng kt ni Chat ID: nickname dng ng nhp

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 19

    Send All : thng tin Chat s c gi ti tt c cc user trong phng Chat

    Send PM: thng tin Chat s c gi ti user c ch nh trong phng Chat

    File/Exit : thot khi phng Chat

    2.3.2. Xy dng cc chc nng

    Xy dng chng trnh Client(s dng lp java.net.Socket): M mt socket ni kt n Server bit a ch IP/localhost v s hiu

    cng(9999). Ly Stream nhp v Stream xut c gn vi socket. Trao i d liu vi Server nh vo cc Stream nhp v Stream xut. Dng giao thc TCP/IP kim tra d liu trao i vi Server. Xy dng chng trnh Server a tuyn(Server phi lun gi kt ni) X l cc yu cu ni kt: Lng nghe yu cu ni kt. Chp nhn mt yu cu ni kt. To knh giao tip o vi cc Client. X l cc thng ip yu cu t Client. X l cc thng ip yu cu t Client: Ch nhn thng ip ca cc Client. Phn tch v x l yu cu. Gi thng ip tr li cho Client.

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 20

    Chng 3. TRIN KHAI V NH GI KT QU

    3.1. Mi trng trin khai H iu hnh Microsoft Windowns 7 profesional, Microsoft Windowns.

    XP.

    Eclipse , Netbeans

    JDK 1.5

    Mng LAN

    3.2. Kt qu cc chc nng ca chng trnh

    Hnh 13 : Kt ni li khi Server cha chy

    Hnh 14 : Chy chng trnh server

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 21

    Hnh 15 : Login thnh cng vo phng Chat

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 22

    Hnh 16 : Th nghim Chat private

    Hnh 17 : Hin th thng bo login v logout trn Server

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 23

    KT LUN V HNG PHT TRIN

    1. Nhng kt qu t c - M phng c m hnh Client-Server trong mng LAN. - Thc hin c yu cu bi ra(CHAT ROOM). - Dng giao thc TCP/IP trong truyn d liu. - Thc hin c vic kim tra trong ni kt gia Client-Server.

    2. Nhng vn tn ti - Chng trnh Chat cn n gin - Giao din s si - Ch thc hin c ni kt gia Client-Server(theo m hnh).

    3. Hng pht trin - Hon thin giao din p v ph hp vi ngi dng. - M rng ng dng trong chng trnh Chat nh : + X l truyn file thng qua chng trnh Chat + Xy dng h c s d liu qun l thng tin ng nhp (

    username, password ) - Pht trin trn mng rng ngoi LAN.

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 24

    PH LC

    1. Chng trnh Server: 1.1. Chatserver class:

    /*

    * To change this template, choose Tools | Templates

    * and open the template in the editor.

    */

    package server;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    import java.io.IOException;

    import java.net.*;

    import java.util.logging.Level;

    import java.util.logging.Logger;

    /**

    *

    * @author anhtuan

    */

    public class chatserver implements Runnable{

    serverSocket sThread[] = new serverSocket[50];

    int maxClient = 0;

    public synchronized void send(String username,String message){

    if ( username.equals("send_to_all")) {

    for(int i=0; i

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 25

    }

    }

    }

    public synchronized void sendToOther(String username, String

    message){

    for(int i=0; i

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 26

    //

    // Command :

    // request_login|username

    // send_all|message

    // send_pm|username|message

    // logout|username

    // list_request

    String st[] = inputString.split("\\|");

    result = true;

    if ((st[0].equals("request_login"))&&maxClient>0) {

    for ( int i =0; i< maxClient; i++ ){

    if ( sThread[i].userID.equals(st[1]) ) {

    result = false;

    break;

    }

    }

    }

    if (result){

    output.writeUTF("OK");

    sThread[maxClient] = new serverSocket(this,socket,st[1]);

    sThread[maxClient].start();

    maxClient++;

    System.out.println("IP :

    "+socket.getInetAddress().getHostAddress() + " | User ID : " + st[1] + ", has

    login in the server.");

    sendToOther(st[1], "updateList|");

    }

    else

    {

    output.writeUTF("Duplicated ID");

    System.out.println("IP :

    "+socket.getInetAddress().getHostAddress() + " | User ID : " + st[1] + ",

    cannot login as duplicated of username.");

    }

    }

    }

    catch (IOException ex) {

    Logger.getLogger(chatserver.class.getName()).log(Level.SEVERE, null, ex);

    }

    }

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 27

    /**

    * @param args the command line arguments

    */

    public static void main(String[] args) {

    new server.chatserver().run();

    }

    }

    1.2. serverSocket class:

    /*

    * To change this template, choose Tools | Templates

    * and open the template in the editor.

    */

    package server;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    import java.io.IOException;

    import java.net.Socket;

    import java.net.SocketException;

    import java.util.logging.Level;

    import java.util.logging.Logger;

    /**

    *

    * @author anhtuan

    */

    public class serverSocket extends Thread{

    Socket socket = null;

    String userID = null;

    boolean active = true;

    chatserver cs = null;

    public serverSocket(chatserver _cs, Socket incoming, String userID){

    this.socket = incoming;

    this.userID = userID;

    this.active = true;

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 28

    this.cs = _cs;

    }

    DataOutputStream output = null;

    public void send(String message){

    try {

    output = new DataOutputStream(socket.getOutputStream());

    output.writeUTF(message);

    } catch (IOException ex) {

    Logger.getLogger(serverSocket.class.getName()).log(Level.SEVERE, null,

    ex);

    }

    }

    @Override

    public void run(){

    DataInputStream input = null;

    try {

    input = new DataInputStream(socket.getInputStream());

    output = new DataOutputStream(socket.getOutputStream());

    while ((true)&&(this.active)){

    String inputString = input.readUTF();

    String[] st = inputString.split("\\|"); // Special character to

    split - Hechay

    // System.out.println(st[0]);

    ////////// list_request ////////////////

    if ( st[0].equals("list_request") ) {

    String sendSt = cs.getAliveHost();

    // System.out.println(sendSt);

    output.writeUTF(sendSt);

    }

    ////////////////////////////////////////

    if ( st[0].equals("send_all") ) {

    cs.send("send_to_all", "normal|" + this.userID + " : " +st[1]

    + "\n");

    }

    ////////////////////////////////////////

    ////////////////////////////////////////

    if ( st[0].equals("send_pm") ) {

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 29

    cs.send(st[1], "normal|" + "[PRIVATE] " + this.userID + " :

    " + st[2] + "\n");

    }

    ////////////////////////////////////////

    ////////////////////////////////////////

    if ( st[0].equals("logout") ) {

    this.active = false;

    System.out.println("IP :

    "+socket.getInetAddress().getHostAddress() + " | User ID : " + this.userID +

    ", left the chat room.");

    this.userID = "Anhtuan-NO-USED-!@#$%^&*()_+";

    cs.send("send_to_all", "updateList|");

    break;

    }

    ////////////////////////////////////////

    }

    } catch (IOException ex) {

    //

    Logger.getLogger(serverThread.class.getName()).log(Level.SEVERE, null,

    ex);

    System.out.println("Someone is disconnected but I haven't

    received the logoff messsage");

    }

    }

    }

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 30

    2. Chng trnh Client 2.1. Client class:

    /*

    * To change this template, choose Tools | Templates

    * and open the template in the editor.

    */

    package client;

    import java.io.*;

    import java.net.*;

    import java.util.logging.Level;

    import java.util.logging.Logger;

    import javax.swing.JList;

    import javax.swing.JOptionPane;

    /**

    *

    * @author anhtuan

    */

    public class Client extends javax.swing.JFrame implements Runnable {

    Socket socket = null;

    String username = null;

    public void run() {

    DataOutputStream output = null;

    try {

    output = new DataOutputStream(socket.getOutputStream());

    DataInputStream input = new

    DataInputStream(socket.getInputStream());

    String sendSt = "list_request";

    output.writeUTF(sendSt+"|");

    String st[] = new String[50];

    String receive = input.readUTF();

    st = receive.split("\\|");

    jList1.setListData(st);

    } catch (IOException ex) {

    Logger.getLogger(Client.class.getName()).log(Level.SEVERE,

    null, ex);

    }

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 31

    }

    Thread thread = null;

    public Client(Socket socket, String username) {

    initComponents();

    this.setLocationRelativeTo(null);

    jList1.removeAll();

    this.socket = socket;

    this.username = username;

    new Thread(this).start();

    thread = new Thread(new clientSocket(socket,jTextArea1,jList1));

    thread.start();

    this.setTitle("Your ID : " + username);

    jTextField2.requestFocus();

    }

    /** This method is called from within the constructor to

    * initialize the form.

    * WARNING: Do NOT modify this code. The content of this method

    is

    * always regenerated by the Form Editor.

    */

    @SuppressWarnings("unchecked")

    // //GEN-BEGIN:initComponents

    private void initComponents() {

    jScrollPane1 = new javax.swing.JScrollPane();

    jList1 = new javax.swing.JList();

    jTextField2 = new javax.swing.JTextField();

    jButton1 = new javax.swing.JButton();

    jButton2 = new javax.swing.JButton();

    jScrollPane2 = new javax.swing.JScrollPane();

    jTextArea1 = new javax.swing.JTextArea();

    jMenuBar1 = new javax.swing.JMenuBar();

    jMenu1 = new javax.swing.JMenu();

    jMenuItem2 = new javax.swing.JMenuItem();

    jMenu2 = new javax.swing.JMenu();

    jMenuItem1 = new javax.swing.JMenuItem();

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 32

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOS

    E);

    addWindowListener(new java.awt.event.WindowAdapter() {

    public void windowClosing(java.awt.event.WindowEvent evt) {

    formWindowClosing(evt);

    }

    });

    jList1.setModel(new javax.swing.AbstractListModel() {

    String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item

    5" };

    public int getSize() { return strings.length; }

    public Object getElementAt(int i) { return strings[i]; }

    });

    jList1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECT

    ION);

    jScrollPane1.setViewportView(jList1);

    jTextField2.addActionListener(new

    java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent evt) {

    jTextField2ActionPerformed(evt);

    }

    });

    jTextField2.addKeyListener(new java.awt.event.KeyAdapter() {

    public void keyPressed(java.awt.event.KeyEvent evt) {

    jTextField2KeyPressed(evt);

    }

    });

    jButton1.setText("Send All");

    jButton1.addActionListener(new java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent evt) {

    jButton1ActionPerformed(evt);

    }

    });

    jButton2.setText("Send PM");

    jButton2.addActionListener(new java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent evt) {

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 33

    jButton2ActionPerformed(evt);

    }

    });

    jTextArea1.setColumns(20);

    jTextArea1.setEditable(false);

    jTextArea1.setRows(5);

    jScrollPane2.setViewportView(jTextArea1);

    jMenu1.setText("File");

    jMenuItem2.setText("Exit");

    jMenuItem2.addActionListener(new

    java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent evt) {

    jMenuItem2ActionPerformed(evt);

    }

    });

    jMenu1.add(jMenuItem2);

    jMenuBar1.add(jMenu1);

    jMenu2.setText("Help");

    jMenuItem1.setText("About");

    jMenuItem1.addActionListener(new

    java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent evt) {

    jMenuItem1ActionPerformed(evt);

    }

    });

    jMenu2.add(jMenuItem1);

    jMenuBar1.add(jMenu2);

    setJMenuBar(jMenuBar1);

    javax.swing.GroupLayout layout = new

    javax.swing.GroupLayout(getContentPane());

    getContentPane().setLayout(layout);

    layout.setHorizontalGroup(

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 34

    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

    .addGroup(layout.createSequentialGroup()

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    LEADING)

    .addGroup(layout.createSequentialGroup()

    .addGap(10, 10, 10)

    .addComponent(jTextField2,

    javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE))

    .addComponent(jScrollPane2,

    javax.swing.GroupLayout.Alignment.TRAILING,

    javax.swing.GroupLayout.DEFAULT_SIZE, 370, Short.MAX_VALUE))

    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELA

    TED)

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    LEADING)

    .addComponent(jScrollPane1,

    javax.swing.GroupLayout.DEFAULT_SIZE, 73, Short.MAX_VALUE)

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    LEADING, false)

    .addComponent(jButton2,

    javax.swing.GroupLayout.DEFAULT_SIZE,

    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)

    .addComponent(jButton1,

    javax.swing.GroupLayout.DEFAULT_SIZE,

    javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))

    .addContainerGap())

    );

    layout.setVerticalGroup(

    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

    .addGroup(layout.createSequentialGroup()

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    LEADING)

    .addComponent(jScrollPane2,

    javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 35

    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,

    layout.createSequentialGroup()

    .addComponent(jScrollPane1,

    javax.swing.GroupLayout.DEFAULT_SIZE, 137, Short.MAX_VALUE)

    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELA

    TED)

    .addComponent(jButton2)))

    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELA

    TED)

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    BASELINE)

    .addComponent(jTextField2,

    javax.swing.GroupLayout.PREFERRED_SIZE,

    javax.swing.GroupLayout.DEFAULT_SIZE,

    javax.swing.GroupLayout.PREFERRED_SIZE)

    .addComponent(jButton1))

    .addContainerGap())

    );

    pack();

    }// //GEN-END:initComponents

    private void

    jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-

    FIRST:event_jMenuItem2ActionPerformed

    formWindowClosing(null);

    System.exit(0);

    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent

    evt) {//GEN-FIRST:event_jButton2ActionPerformed

    if

    ((!jList1.isSelectionEmpty())&&(!jTextField2.getText().equals(""))) {

    String selected = (String)jList1.getSelectedValue();

    if ( !selected.equals(this.username) ) {

    DataOutputStream output = null;

    try {

    //send_pm|username|message

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 36

    String sendSt = "send_pm|";

    sendSt += (String) jList1.getSelectedValue() + "|";

    sendSt += jTextField2.getText();

    output = new

    DataOutputStream(socket.getOutputStream());

    output.writeUTF(sendSt);

    jTextArea1.append("[PRIVATE-"+selected+"] " +

    jTextField2.getText() );

    jTextField2.setText("");

    } catch (IOException ex) {

    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);

    }

    }

    else{

    JOptionPane.showMessageDialog(null, "You cannot send PM

    to yourself!");

    }

    }

    else

    {

    JOptionPane.showMessageDialog(null, "No User ID Is Selected

    or No Message!");

    }

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent

    evt) {//GEN-FIRST:event_jButton1ActionPerformed

    if (!jTextField2.getText().equals(""))

    {

    try {

    // TODO add your handling code here:

    DataOutputStream output = new

    DataOutputStream(socket.getOutputStream());

    output.writeUTF("send_all|"+jTextField2.getText());

    jTextField2.setText("");

    } catch (IOException ex) {

    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);

    }

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 37

    }

    else

    {

    JOptionPane.showMessageDialog(null, "No message !");

    }

    }//GEN-LAST:event_jButton1ActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt)

    {//GEN-FIRST:event_formWindowClosing

    // TODO add your handling code here:

    if (this.socket != null) {

    DataOutputStream output = null;

    try {

    output = new DataOutputStream(socket.getOutputStream());

    output.writeUTF("logout|");

    thread.interrupt();

    } catch (IOException ex) {

    Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);

    }

    }

    }//GEN-LAST:event_formWindowClosing

    private void jTextField2KeyPressed(java.awt.event.KeyEvent evt)

    {//GEN-FIRST:event_jTextField2KeyPressed

    // TODO add your handling code here:

    }//GEN-LAST:event_jTextField2KeyPressed

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent

    evt) {//GEN-FIRST:event_jTextField2ActionPerformed

    // TODO add your handling code here:

    jButton1ActionPerformed(null);

    }//GEN-LAST:event_jTextField2ActionPerformed

    private void

    jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-

    FIRST:event_jMenuItem1ActionPerformed

    // TODO add your handling code here:

    new About().setVisible(true);

    }//GEN-LAST:event_jMenuItem1ActionPerformed

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 38

    /**

    * @param args the command line arguments

    */

    public static void main(String args[]) {

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables

    private javax.swing.JButton jButton1;

    private javax.swing.JButton jButton2;

    private javax.swing.JList jList1;

    private javax.swing.JMenu jMenu1;

    private javax.swing.JMenu jMenu2;

    private javax.swing.JMenuBar jMenuBar1;

    private javax.swing.JMenuItem jMenuItem1;

    private javax.swing.JMenuItem jMenuItem2;

    private javax.swing.JScrollPane jScrollPane1;

    private javax.swing.JScrollPane jScrollPane2;

    private javax.swing.JTextArea jTextArea1;

    private javax.swing.JTextField jTextField2;

    // End of variables declaration//GEN-END:variables

    }

    2.2. ClientLogin class:

    /*

    * To change this template, choose Tools | Templates

    * and open the template in the editor.

    */

    package client;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    import java.io.IOException;

    import java.net.*;

    import java.util.logging.Level;

    import java.util.logging.Logger;

    import javax.swing.JOptionPane;

    /**

    *

    * @author anhtuan

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 39

    */

    public class ClientLogin extends javax.swing.JFrame {

    /** Creates new form ClientLogin */

    public ClientLogin() {

    initComponents();

    this.setLocationRelativeTo(null);

    jTextField3.requestFocus();

    }

    /** This method is called from within the constructor to

    * initialize the form.

    * WARNING: Do NOT modify this code. ssThe content of this

    method is

    * always regenerated by the Form Editor.

    */

    @SuppressWarnings("unchecked")

    // //GEN-BEGIN:initComponents

    private void initComponents() {

    jTextField1 = new javax.swing.JTextField();

    jLabel1 = new javax.swing.JLabel();

    jLabel2 = new javax.swing.JLabel();

    jTextField2 = new javax.swing.JTextField();

    jTextField3 = new javax.swing.JTextField();

    jLabel3 = new javax.swing.JLabel();

    jButton1 = new javax.swing.JButton();

    jButton2 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOS

    E);

    setTitle("Client Login");

    jTextField1.setText("127.0.0.1");

    jLabel1.setText("Server IP/Hostname");

    jLabel2.setText("Port");

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 40

    jTextField2.setEditable(false);

    jTextField2.setText("9999");

    jLabel3.setText("Chat ID");

    jButton1.setText("Login");

    jButton1.addActionListener(new java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent evt) {

    jButton1ActionPerformed(evt);

    }

    });

    jButton2.setText("Exit");

    jButton2.addActionListener(new java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent evt) {

    jButton2ActionPerformed(evt);

    }

    });

    javax.swing.GroupLayout layout = new

    javax.swing.GroupLayout(getContentPane());

    getContentPane().setLayout(layout);

    layout.setHorizontalGroup(

    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

    .addGroup(layout.createSequentialGroup()

    .addGap(26, 26, 26)

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    LEADING)

    .addGroup(layout.createSequentialGroup()

    .addComponent(jButton1)

    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED

    )

    .addComponent(jButton2))

    .addGroup(layout.createSequentialGroup()

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    LEADING)

    .addComponent(jLabel1)

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 41

    .addComponent(jLabel2)

    .addComponent(jLabel3))

    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED

    )

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    LEADING)

    .addComponent(jTextField1,

    javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE)

    .addComponent(jTextField2,

    javax.swing.GroupLayout.PREFERRED_SIZE, 40,

    javax.swing.GroupLayout.PREFERRED_SIZE)

    .addComponent(jTextField3,

    javax.swing.GroupLayout.DEFAULT_SIZE, 118, Short.MAX_VALUE))))

    .addGap(22, 22, 22))

    );

    layout.setVerticalGroup(

    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

    .addGroup(layout.createSequentialGroup()

    .addContainerGap()

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    BASELINE)

    .addComponent(jLabel1)

    .addComponent(jTextField1,

    javax.swing.GroupLayout.PREFERRED_SIZE,

    javax.swing.GroupLayout.DEFAULT_SIZE,

    javax.swing.GroupLayout.PREFERRED_SIZE))

    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED

    )

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    BASELINE)

    .addComponent(jTextField2,

    javax.swing.GroupLayout.PREFERRED_SIZE,

    javax.swing.GroupLayout.DEFAULT_SIZE,

    javax.swing.GroupLayout.PREFERRED_SIZE)

    .addComponent(jLabel2))

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 42

    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED

    )

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    BASELINE)

    .addComponent(jTextField3,

    javax.swing.GroupLayout.PREFERRED_SIZE,

    javax.swing.GroupLayout.DEFAULT_SIZE,

    javax.swing.GroupLayout.PREFERRED_SIZE)

    .addComponent(jLabel3))

    .addGap(18, 18, 18)

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    BASELINE)

    .addComponent(jButton1)

    .addComponent(jButton2))

    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,

    Short.MAX_VALUE))

    );

    pack();

    }// //GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent

    evt) {//GEN-FIRST:event_jButton2ActionPerformed

    // TODO add your handling code here:

    System.exit(0);

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent

    evt) {//GEN-FIRST:event_jButton1ActionPerformed

    if (jTextField3.getText().equals("")){

    JOptionPane.showMessageDialog(null, "User ID cannot be

    blank !");

    }

    else

    {

    try {

    // TODO add your handling code here:

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 43

    // Send the request to the server, if the userid is duplicate,

    program will ask to change userID

    String serverIP = jTextField1.getText();

    int serverPort = Integer.parseInt(jTextField2.getText());

    Socket socket = new Socket(serverIP, serverPort);

    String request = "request_login|"+jTextField3.getText();

    DataInputStream input = new

    DataInputStream(socket.getInputStream());

    DataOutputStream output = new

    DataOutputStream(socket.getOutputStream());

    output.writeUTF(request);

    String receive = input.readUTF();

    if (receive.equals("OK")){

    new Client(socket,jTextField3.getText()).setVisible(true);

    dispose();

    }

    else

    {

    JOptionPane.showMessageDialog(null, receive, "Error", 0);

    }

    } catch (UnknownHostException ex) {

    //Logger.getLogger(ClientLogin.class.getName()).log(Level.SEVERE, null,

    ex);

    JOptionPane.showMessageDialog(null, "Network got

    problems. Try again ...");

    } catch (IOException ex) {

    //Logger.getLogger(ClientLogin.class.getName()).log(Level.SEVERE, null,

    ex);

    JOptionPane.showMessageDialog(null, "Network got

    problems. Try again ...");

    }

    }

    }//GEN-LAST:event_jButton1ActionPerformed

    /**

    * @param args the command line arguments

    */

    public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {

    public void run() {

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 44

    new ClientLogin().setVisible(true);

    }

    });

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables

    private javax.swing.JButton jButton1;

    private javax.swing.JButton jButton2;

    private javax.swing.JButton jButton3;

    private javax.swing.JLabel jLabel1;

    private javax.swing.JLabel jLabel2;

    private javax.swing.JLabel jLabel3;

    private javax.swing.JTextField jTextField1;

    private javax.swing.JTextField jTextField2;

    private javax.swing.JTextField jTextField3;

    // End of variables declaration//GEN-END:variables

    }

    2.3. clientSocket

    /*

    * To change this template, choose Tools | Templates

    * and open the template in the editor.

    */

    package client;

    import java.io.DataInputStream;

    import java.io.DataOutputStream;

    import java.io.IOException;

    import java.net.*;

    import java.util.logging.Level;

    import java.util.logging.Logger;

    import javax.swing.JList;

    import javax.swing.JTextArea;

    /**

    *

    * @author anhtuan

    */

    public class clientSocket implements Runnable {

    Socket socket = null;

    JTextArea chatArea = null;

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 45

    JList list = null;

    public clientSocket(Socket socket, JTextArea chatArea,JList list){

    this.socket = socket;

    this.chatArea = chatArea;

    this.list = list;

    }

    public void run() {

    try {

    DataInputStream input = new

    DataInputStream(socket.getInputStream());

    while(true){

    if (!socket.isInputShutdown()){

    String receive = input.readUTF();

    String st[] = receive.split("\\|");

    // Normal message ////////////

    if (st[0].equals("normal")) {

    chatArea.append(st[1]);

    }

    //////////////////////////////

    // List Command

    if (st[0].equals("updateList")) {

    DataOutputStream output = new

    DataOutputStream(socket.getOutputStream());

    String sendSt = "list_request";

    output.writeUTF(sendSt+"|");

    String st1[] = new String[50];

    String receive1 = input.readUTF();

    st1 = receive1.split("\\|");

    list.removeAll();

    list.setListData(st1);

    }

    //////////////////////////////

    }

    }

    } catch (IOException ex) {

    Logger.getLogger(clientSocket.class.getName()).log(Level.SEVERE, null,

    ex);

    }

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 46

    }

    }

    About class

    /*

    * To change this template, choose Tools | Templates

    * and open the template in the editor.

    */

    package client;

    /**

    *

    * @author anhtuan

    */

    public class About extends javax.swing.JFrame {

    /** Creates new form About */

    public About() {

    initComponents();

    this.setLocationRelativeTo(null);

    }

    /** This method is called from within the constructor to

    * initialize the form.

    * WARNING: Do NOT modify this code. The content of this method

    is

    * always regenerated by the Form Editor.

    */

    @SuppressWarnings("unchecked")

    // //GEN-BEGIN:initComponents

    private void initComponents() {

    jLabel1 = new javax.swing.JLabel();

    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOS

    E);

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 47

    setTitle("About");

    jLabel1.setText("This product was developed by Tran Anh Tuan");

    jButton1.setText("OK");

    jButton1.addActionListener(new java.awt.event.ActionListener() {

    public void actionPerformed(java.awt.event.ActionEvent evt) {

    jButton1ActionPerformed(evt);

    }

    });

    javax.swing.GroupLayout layout = new

    javax.swing.GroupLayout(getContentPane());

    getContentPane().setLayout(layout);

    layout.setHorizontalGroup(

    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

    .addGroup(layout.createSequentialGroup()

    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.

    LEADING)

    .addGroup(layout.createSequentialGroup()

    .addContainerGap()

    .addComponent(jLabel1))

    .addGroup(layout.createSequentialGroup()

    .addGap(90, 90, 90)

    .addComponent(jButton1,

    javax.swing.GroupLayout.PREFERRED_SIZE, 108,

    javax.swing.GroupLayout.PREFERRED_SIZE)))

    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,

    Short.MAX_VALUE))

    );

    layout.setVerticalGroup(

    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

    .addGroup(layout.createSequentialGroup()

    .addContainerGap()

    .addComponent(jLabel1)

    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED

    )

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 48

    .addComponent(jButton1)

    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,

    Short.MAX_VALUE))

    );

    pack();

    }// //GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent

    evt) {//GEN-FIRST:event_jButton1ActionPerformed

    // TODO add your handling code here:

    this.dispose();

    }//GEN-LAST:event_jButton1ActionPerformed

    /**

    * @param args the command line arguments

    */

    public static void main(String args[]) {

    java.awt.EventQueue.invokeLater(new Runnable() {

    public void run() {

    new About().setVisible(true);

    }

    });

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables

    private javax.swing.JButton jButton1;

    private javax.swing.JLabel jLabel1;

    // End of variables declaration//GEN-END:variables

    }

  • n Lp Trnh Mng GVHD : Trn H Thy Tin

    Sinh Vin: Trn Anh Tun - Lp 06t3 49

    TI LIU THAM KHO

    http://www.songmay.com/index.php?fs=main&loai=14&sub=2&tieude

    =Mi4gVENQL0lQIGzDoCBnw6w/&chude=RkFRcyAvIEludGVybmV0.

    http://vi.wikipedia.org/wiki/Client-server

    http://vi.wikipedia.org/wiki/TCP#C.E1.BA.A5u_tr.C3.BAc_g.C3.B3i_ti

    n

    http://hpcc.hut.edu.vn/forum/index.php?topic=213.0

    http://www.ebook.edu.vn/?page=1.39&view=179

    http://www.softechaptech.com/forums/viewtopic.php?f=83&t=95