You are on page 1of 30

[TUT]JAVA: Lp trnh TCP Socket

Quote: JAVA: Lp trnh Socket vi TCP Ngi son: Nimbus Ti liu tham kho: 1. Gio trnh Lp trnh Hng i tng JAVA - Ngc Anh Th Press - NXB Thng K 2. Computer Networking - By James F. Kurose and Keith W. Ross - Addison Wesley 3. Website http://www.planet-source-code.com 4. JAVA Lp trnh mng - Nguyn Phng Lan v Hong c Hi - NXB Gio Dc 1.1. Lp trnh Socket vi TCP 1.1.1. Gii thiu Trong phn ny chng ta s tm hiu v s pht trin cc ng dng mng. Ta bit li (core) ca mt ng dng mng bao gm mt cp chng trnh mt chng trnh my khch (client program) v mt chng trnh my ch (server program). Khi c hai chng trnh c thi hnh, tin trnh (process) my khch v my ch c to ra, v hai tin trnh ny lin lc vi nhau bng cch c t v ghi n nhng socket. Khi to ra mt ng dng mng, nhim v ca chng ta l vit m cho c chng trnh my khch v my ch. C hai loi ng dng client-server. Mt loi l nhng ng dng client-server m n c hin thc trn nhng giao thc chun c nh ngha trong cc RFC (Request for Comments). Vi nhng ng dng kiu ny th chng trnh my ch v my khch u phi ph hp vi nhng quy tc c nu ra trong RFC. V d, mt chng trnh my khch c th hin thc mt chng trnh FTP client, c nh ngha trong [RFC 959], v chng trnh my ch th hin thc mt FTP server, cng phi c nh ngha trong [RFC 959] Loi cn li ca mt ng dng client-server l mt ng dng server-client gi c quyn (proprietary). Trng hp ny ng vi ng dng ta thc hin trong bi tp ny. Trong loi ng dng ny th chng trnh my khch ln my ch u khng cn phi ph hp vi bt c RFC no. Mt nh pht trin n l c th to ra c hai chng trnh client v server, v nh pht trin ny hon ton iu khin tt c nhng g c trong m lp trnh. Nhng bi v m lp trnh khng c hin thc trn giao thc chun, nn nhng nh pht trin c lp khc s khng th no pht trin m c th tng thch vi ng dng ny. Khi pht trin mt ng dng kiu ny, nhng nh pht trin phi ch khng s dng nhng cng thng dng c nh ngha trong cc RFC. Trong phn k tip ta s nghin cu nhng im mu cht pht trin mt ng dng clientserver gi c quyn. Trong qu trnh pht trin, mt trong nhng quyt nh quan trng m nh pht trin cn phi lm l ng dng s chy trn TCP hay trn UDP. TCP th hng kt ni (connection-oriented) v cung cp nhng knh lung truyn d liu ng tin m qua d liu s c truyn gia hai h thng cui. UDP l mt giao thc khng kt ni v gi i nhng gi d liu c lp t h thng cui ny n nhng h thng cn li, m khng h bo m d liu c c nhn hay khng. Trong khun kh bi tp ny th ta ch nghin cu mt ng dng nh chy trn TCP. ng dng nh ny c vit bng ngn ng Java, ta chn Java v nhng l do sau y. Th nht, nhng ng dng mng kiu ny s gn gng hn khi vit bng Java; vi Java s c t dng m hn, v mi dng c th d dng gii thch vi c nhng ngi lp trnh mi bt u. Th hai,

nhng chng trnh client-server lp trnh bng Java gia tng ngy cng thng dng, v n c th tr thnh tiu chun cho lp trnh mng trong vi nm ti. Java l mt ngn ng c lp nn tng, n c c ch by li (iu qun cc ngoi l) cng trng m c th gii quyt hu n cc li xy ra trong qu trnh xut/nhp v nhng hot ng mng, v kh nng phn lung (thread) mnh cung cp nhng phng php n gin hin thc nhng server mnh m. 1.1.2. Lp trnh Socket vi TCP Ta bit rng nhng tin trnh chy trn nhng my khc nhau c th lin lc vi nhay bng cch gi nhng thng ip n socket. Chng ta c th ni mt cch n gin rng mi mt tin trnh th tng t nh mt cn nh v socket ca tin trnh th tng t nh l cnh ca nh. Nh th hin trn hnh v bn di, socket l cnh ca gia tin trnh ng dng (Application Process) v TCP. Nhng nh pht trin ng dng c th kim sot mi th bn pha lp Application ca Socket; tuy nhin, c rt t kim sot bn pha lp Transport. By gi ta hy xt k hn s tng tc gia chng trnh client v chng trnh server. My khch client phi c nhim v khi to s giao tip vi server. server c th tr li li s giao tip ban u ny th server cng phi lun lun sn sng. iu ny bao gm 2 yu t. u tin, chng trnh bn server phi ang hot ng, n phi ang chy nh mt tin trnh trc khi my khch tin hnh s giao tip u tin. Th hai, chng trnh bn server phi c sn mt s cng (port) c th tip n (welcome) nhng giao tip khi to t bn pha client. S dng s tng t nh cn nh/cnh ca i vi process/socket nh ni trn th ta c th xem nh s khi to giao tip u tin bn pha client nh l mt s g ca. Khi mt tin trnh (process) bn server ang chy, mt tin trnh bn client c th khi to mt TCP connection. iu ny c thc bn chng trnh my client bng cch to ra mt i tng socket (ta gi n l clientSocket). Khi mt my khch to ra mt i tng socket th n s ch n a ch ca tin trnh my ch, theo cch gi tn, th l a ch IP ca my server. V cng lc to ra i tng clientSocket th TCP client khi to mt three-way handshake (bi tp mng TCP/IP s gii thiu r hn v cch thc ny) v thit lp mt TCP connection vi server. Three-way handshake ny th hon ton n giu vi c chng trnh server ln chng trnh client. Trong sut qu trnh three-way handshake, tin trnh bn my khch s g vo cng ca tin trnh my ch. Khi server nhn c s g ca ny, n s to ra mt cnh ca mi (tht ra l mt socket mi) m phc v cho tng client chuyn bit. Trong bi tp ny, cnh ca cho n chnh l mt i tng ServerSocket m ta gi l welcomeSocket. Khi mt my khch g ca, chng trnh s vin dn phng thc accept() ca welcomeSocket, phng thc ny s to ra mt socket khc cho client. Vo cui qu trnh handshaking ny th mt kt ni TCP s c thit lp gia socket ca client v mt socket mi ca server. T y tr v sau, ta s gi new socket ny bng tn gi l connection socket TCP connection uc xem nh l mt ng dn o gia clients socket v server's connection socket. Lc ny, tin trnh bn my khch c th gi nhng byte tu n socket ca n, TCP bo m rng tin trnh bn server s nhn (thng qua connection socket) mi byte theo trnh t gi. Hn th na, ngc li tin trnh bn my khch cng c th nhn byte t socket ca n v tin trnh bn server cng c th gi byte n connection socket ca n. iu ny c m t hnh bn di.

Bi v socket ng mt vai tr quan trng trong nhng ng dng client-server, cho nn nhng ng dng client-server thng c gi l socket programming. Trc khi i n ng dng bi tp c th, ta s ni v khi nim lung (stream). Theo ngha en lung l mt dng lu chuyn. Theo ngha k thut, mt lung l mt l trnh qua d liu di chuyn i vo hay i ra mt tin trnh (process). Mi mt lung th c th l mt lung vo (input stream) hay l mt lung xut (output stream) cho mt tin trnh. Nu mt lung l lung vo th n s nh km vi nhng ngun vo ca mt tin trnh, v d nh l mt cng c nhp chun (keyboard) hoc mt socket m d liu i vo n t network. Nu mt lung l lung xut, th n s c nh km vi mt vi ngun xut ca tin trnh, v d nh l mt cng c xut chun (mn hnh) hoc mt socket m i ra t n d liu s i vo network. ======================================= 1.2. Chng trnh v d 1: Giao nhn file bng IP 1.2.1. Cch thc hot ng Chng trnh gm mt file duy nht c tn l FileTransfer.java tc l n ch c mt m ngun cho c hai bn server v client. Sau khi bin dch file .java ny th ta s chy n bng lnh java FileTransfer. Tip theo chng trnh s yu cu ngi dng chn la computer tr thnh client hoc server, c th hin nh trn hnh v. Ta nhp vo 1 nu chn l client v nhp vo 2 nu mun my tnh tr thnh server. Chy chng trnh server mode Tu chn 2 phi c chn trc my tnh c ch nh chy server mode, sau my tnh ny s ch i cc kt ni n n. Ta phi nhp tip port number, ng vi server mode ny th ta c th chn bt c port number no ln hn 1024, v nhng port number di 1024 b gi trc v s dng bi h thng (well-known ports). Chng trnh ny cng c th thc hin giao nhn file gia mt server v nhiu my con ng thi trong mt h thng mng nn n s yu cu ta nhp vo s lng my client ln nht c th kt ni n server ny. Chy chng trnh client mode Tng t cho pha bn client, chng trnh s yu cu nhp vo a ch ca server (host address), ta c th nhp a ch IP hay nhp vo tn ca my chy server mode u c (trong trng hp trn hnh bn di th tn my chy server mode c a ch IP trong mng LAN l 192.168.0.144). Tip tc ta s nhp port number, client phi cng ng chn nhp port number nh bn server nh bn server chn th mi c th giao nhn file c. Giao din giao nhn file Sao khi chn xong bc ny th chng trnh c hai my s hin th mt ca s dng GUI gip cho vic giao nhn file c thc hin d dng. C hai bn server v client u c th gi file bng cch click vo nt Browse chn file v sau click vo nt Send gi file i. Sau khi click Send gi i th chng trnh bn my nhn s hin th mt hp thoi hi ngi dng c chp nhn nhn file hay khng. Theo m t trn hnh v th my sieutoc.mshome.net (my chy server mode c a ch IP 192.168.0.144 nh hnh trn) gi mt file c tn l TestTransferFile.txt cho my khc.

Sau khi chn nhn file xong th chng trnh s tip tc hin mt hp thoi khc na thng bo rng file c gi hay c nhn. File sau khi nhn s c cha trong cng th mc cha file chng trnh. 1.2.2. Hin thc ng dng bng m lp trnh Java: Code: //************************************************** ************************ // Name: File transfer application // Description: transfer files on a network // Source: http://www.planet-source-code.com // File Name: FileTransfer.java //************************************************** ************************ import java.io.*; import java.net.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class FileTransfer extends Frame { public static String strHostAddress = ""; public static int intPortNumber = 0, intMaxClients = 0; public static Vector vecConnectionSockets = null; public static FileTransfer objFileTransfer; public static String strFileName = "",strFilePath = ""; public static int intCheckChoice = 0; public static Socket clientSocket = null; public static ObjectOutputStream outToServer = null; public static ObjectInputStream inFromServer = null;

public static void main (String [] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in)); System.out.println("\nSelect Type for this Computer:"); System.out.println(" 1. Connect to host (i.e This computer is a client)"); System.out.println(" 2. Wait for connections (i.e This computer is a server)"); System.out.println(); System.out.print("Please make a choice: "); System.out.flush(); int intChoice = Integer.parseInt(stdin.readLine());

if (intChoice == 1) { // This computer is a client System.out.print("Please type in the host address: "); System.out.flush(); strHostAddress = stdin.readLine(); System.out.print("Please type in the host port number: "); System.out.flush(); intPortNumber = Integer.parseInt(stdin.readLine()); }

if (intChoice == 2) { //This computer is a server System.out.print("Give the port number to listen for requests: "); System.out.flush(); intPortNumber = Integer.parseInt(stdin.readLine()); System.out.print("Give the maximum number of clients for this server: "); System.out.flush(); intMaxClients = Integer.parseInt(stdin.readLine()); } objFileTransfer = new FileTransfer(intChoice); } public Label lblSelectFile; public Label lblTitle; public Label lblStudentName; public TextField tfFile; public Button btnBrowse; public Button btnSend; public Button btnReset;

public FileTransfer (int c) { setTitle("Java - File Transfer"); setSize(300 , 300); setLayout(null); addWindowListener(new WindowAdapter () { public void windowClosing (WindowEvent e) { System.exit(0); } } ); lblTitle = new Label("FILE TRANSFER BY IP"); add(lblTitle); lblTitle.setBounds(80,30,300,30); lblSelectFile = new Label("Select File:"); add(lblSelectFile); lblSelectFile.setBounds(15,87,100,20);

lblStudentName = new Label("Thanh Thien - Thanh Tuan"); add(lblStudentName); lblStudentName.setBounds(130,270,200,20);

tfFile = new TextField(""); add(tfFile); tfFile.setBounds(13,114,200,20); btnBrowse = new Button("Browse"); btnBrowse.addActionListener(new buttonListener()); add(btnBrowse); btnBrowse.setBounds(223,113,50,20); btnSend = new Button("Send"); btnSend.addActionListener(new buttonListener()); add(btnSend); btnSend.setBounds(64,168,50,20); btnReset = new Button("Reset"); btnReset.addActionListener(new buttonListener()); add(btnReset); btnReset.setBounds(120,168,50,20); show();

if (c == 1) { // Client receives file intCheckChoice = 1;

try { clientSocket = new Socket (strHostAddress,intPortNumber); outToServer = new ObjectOutputStream(clientSocket.getOutputStream()) ; outToServer.flush(); inFromServer = new ObjectInputStream(clientSocket.getInputStream()); int intFlag = 0;

while (true) { Object objRecieved = inFromServer.readObject();

switch (intFlag) { case 0:

if (objRecieved.equals("IsFileTransfered")) { intFlag++; } break; case 1: strFileName = (String) objRecieved; int intOption = JOptionPane.showConfirmDialog(this,clientSocket.ge tInetAddress().getHostName()+" is sending you "+strFileName+"!\nDo you want to recieve it?","Recieve Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUE STION_MESSAGE); if (intOption == JOptionPane.YES_OPTION) { intFlag++; } else { intFlag = 0; } break; case 2: byte[] arrByteOfReceivedFile = (byte[])objRecieved; FileOutputStream outToHardDisk = new FileOutputStream(strFileName); outToHardDisk.write(arrByteOfReceivedFile); intFlag = 0; JOptionPane.showMessageDialog(this,"File Recieved!","Confirmation",JOptionPane.INFORMATION_ MESSAGE); break; } Thread.yield(); } } catch (Exception e) {System.out.println(e);} }

if (c == 2) { // Server receives file vecConnectionSockets = new Vector(); intCheckChoice = 2; try { ServerSocket welcomeSocket = new ServerSocket(intPortNumber,intMaxClients); while (true) { vecConnectionSockets.addElement(new ThreadedConnectionSocket(welcomeSocket.accept())); Thread.yield(); } } catch (IOException ioe) {System.out.println(ioe);} }

public static String showDialog () { FileDialog fd = new FileDialog(new Frame(),"Select File...",FileDialog.LOAD); fd.show(); return fd.getDirectory()+fd.getFile(); }

private class buttonListener implements ActionListener {

public void actionPerformed (ActionEvent ae) { byte[] arrByteOfSentFile = null;

if (ae.getSource() == btnBrowse) { strFilePath = showDialog(); tfFile.setText(strFilePath); int intIndex = strFilePath.lastIndexOf("\\"); strFileName = strFilePath.substring(intIndex+1); }

if (ae.getSource() == btnSend) { try { FileInputStream inFromHardDisk = new FileInputStream (strFilePath); int size = inFromHardDisk.available(); arrByteOfSentFile = new byte[size]; inFromHardDisk.read(arrByteOfSentFile,0,size); if (intCheckChoice == 2) {// Send file from server

for (int i=0;i<vecConnectionSockets.size();i++) { ThreadedConnectionSocket tempConnectionSocket = (ThreadedConnectionSocket)vecConnectionSockets.ele mentAt(i); tempConnectionSocket.outToClient.writeObject("IsFi leTransfered"); tempConnectionSocket.outToClient.flush(); tempConnectionSocket.outToClient.writeObject(strFi leName); tempConnectionSocket.outToClient.flush(); tempConnectionSocket.outToClient.writeObject(arrBy teOfSentFile); tempConnectionSocket.outToClient.flush(); }

} if (intCheckChoice == 1) { // Send file from client outToServer.writeObject("IsFileTransfered"); outToServer.flush(); outToServer.writeObject(strFileName); outToServer.flush(); outToServer.writeObject(arrByteOfSentFile); outToServer.flush(); } JOptionPane.showMessageDialog(null,"File Sent!","Confirmation",JOptionPane.INFORMATION_MESS AGE); } catch (Exception ex) {} } if (ae.getSource() == btnReset) { tfFile.setText(""); } } } }

class ThreadedConnectionSocket extends Thread { public Socket connectionSocket; public ObjectInputStream inFromClient; public ObjectOutputStream outToClient;

public ThreadedConnectionSocket (Socket s) { connectionSocket = s;

try { outToClient = new ObjectOutputStream(connectionSocket.getOutputStrea m()); outToClient.flush(); inFromClient = new ObjectInputStream(connectionSocket.getInputStream( )); } catch (Exception e) {System.out.println(e);} start(); }

public void run () {

try { int intFlag = 0; String strFileName = "";

while (true) { Object objRecieved = inFromClient.readObject();

switch (intFlag) { case 0:

if (objRecieved.equals("IsFileTransfered")) { intFlag++; } break; case 1: strFileName = (String) objRecieved; int intOption = JOptionPane.showConfirmDialog(null,connectionSocke t.getInetAddress().getHostName()+" is sending you "+strFileName+"!\nDo you want to recieve it?","Recieve Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUE STION_MESSAGE);

if (intOption == JOptionPane.YES_OPTION) { intFlag++;

} else { intFlag = 0; } break; case 2: byte[] arrByteOfReceivedFile = (byte[])objRecieved; FileOutputStream outToHardDisk = new FileOutputStream(strFileName); outToHardDisk.write(arrByteOfReceivedFile); intFlag = 0; JOptionPane.showMessageDialog(null,"File Recieved!","Confirmation",JOptionPane.INFORMATION_ MESSAGE); break; } Thread.yield(); } } catch (Exception e) {System.out.println(e);} }

} ================================================== ======== 1.2.3. Gii thch phn hin thc chng trnh Chng ta s nghin cu chi tit, tng dng mt trong m chng trnh hiu r c ch hot ng ca n. Tuy nhin c th d dng nm bt n th ta s nu mt s im mu cht trong chng trnh 1.2.3.1 Nhng im mu cht ca chng trnh Ti my chy client mode Chng trnh s ti ra 4 stream v mt socket c biu din nh hnh v: Xt qu trnh gi file: Socket th c gi l clientSocket. Cn lung (stream) inFromHardDisk c kiu l FileInputStream, l mt lung nhp n chng trnh; n th nh km vi cng my tnh. Mt khi ta chn c ng dn v tn file th d liu ca file s c chy vo lung inFromHardDisk. Cn lung outToServer c kiu l ObjectOutputStream l mt lung xut ca chng trnh; n c nh km vi clientSocket. D liu m client gi n mng chy trong lung outToServer. Xt qu trnh nhn File: Lung inFromServer c kiu l ObjectInputStream, l mt lung nhp n chng trnh; n c nh km vi socket. D liu n t network s chy vo lung inFromServer. Cn lung outToHardDisk c kiu l FileOutputStream, l lung xut ca chng trnh; n c nh km vi cng, d liu t lung inFromServer s i vo lung outToHardDisk, t n s ghi file ra cng my tnh Ti my chy server mode Chng trnh s ti ra 4 stream v mt socket c biu din nh hnh v: Qu trnh giao nhn file v send file cng din ra tng t nh bn client vi 4 lung inFromHardDisk, outToHardDisk, inFromClient, outToClient v connectionSocket c biu din nh trn hnh v. y ta s khng trnh by li. Ch c mt ch quan trng l trong ng dng ny cho php giao nhn file gia mt server v nhiu my con ng thi trong mt h thng mng nn ti u ho qu trnh hot ng th ta khai bo thm mt lp na gi l ThreadedConnectionSocket, lp ny nh ngha mt i tng socket cng tng t nh connectionSocket m t trn nhng lp ny l lp m rng ca lp Thread, iu ny s tn dng c tnh nng a xu (multithreading) ca Java. V nhng ThreadedConnectionSocket li c a vo lp Vector. Kt qu l ta c th giao nhn file gia mt server v nhiu client trong mt mng vi tc x l ti u. 1.2.3.2 Phn tch chi tit m ngun ca chng trnh 2.3.2.1. Qu trnh khai bo v to i tng import java.io.*; import java.net.*; import java.util.*;

java.io v java.net l nhng gi trong Java. Gi java.io cha cc lp cho cc lung xut v lung nhp. C th l, gi java.io cha cc lp ObjectOutputStream, ObjectInputStream, FileInputStream, FileOutputStream, nhng lp ny c s dng v m t trn. Cn gi java.net th cung cp nhng lp h tr mng. C th l, n cha cc lp Socket v ServerSocket. i tng clientSocket trong chng trnh ny l mt s dn xut t lp Socket. Cn gi java.util th cha mt vi lp hu ch nht m ta s da vo n. Trong chng trnh ny ta c s dng lp Vector ca gi ny. import java.awt.*; import java.awt.event.*; import javax.swing.*; Gi java.awt.* cha nhng lp to ra giao din ngi dng ho (GUI), to ra mt giao din hnh nh d lm vic. Mt thnh phn GUI l mt i tng hnh nh m ngi dng tng tc vi n thng qua chut hoc bn phm. Cc thnh phn ny c th l cc nt (button), nhn (label), trng vn bn (TextField) v.v... Cn java.awt.event.* gip iu qun cc s kin, khi ngi dng thc hin mt hnh ng nh di chut, nhn phm, nh phm ... Tt c cc hnh ng ny to ra mt s kin. C mt s s kin cn c chng trnh iu qun mt cch r rt, ta s phn tch k iu ny khi i vo tng dng m c th. Cn Swing chnh l mt s b sung AWT, n cung cp cho ta nhiu thnh phn giao din ngi dng khc m AWT khng c. Trong chng trnh ny ta c s dng thnh phn JOptionPane ca Swing. public class FileTransfer extends Frame { public static String strHostAddress = ""; public static int intPortNumber = 0, intMaxClients = 0; public static Vector vecConnectionSockets = null; ngha ca nhng dng m trn l ta khai bo mt lp FileTransfer chnh cho chng trnh, lp ny lp m rng ca lp Frame. Mt Frame l mt ca s c lp. Cc khung thng c dng trong cc ng dng yu cu giao din ngi dng ho. Tip theo ta khai bo cc bin thuc tnh cho class ny, strHostAddress l a ch ca server m client kt ni n, intPortNumber l s th t ca cng giao nhn d liu, intMaxClients l s my client ti a kt ni n server cc bin ny s c gn t pha ngi dng. Cn vecConnectionSockets l mt Vector cha cc ThreadedConnectionSocket h tr cho vic nhiu my client kt ni n mt my ch nh bn trn. Trong trng hp ny ta dng kiu Vector v lp Java Vector cung cp mt dng mng chnh c c c th tng trng khi c thm mt phn t c b sung vo n. public static FileTransfer objFileTransfer; Cn objFileTransfer l mt i tng thuc chnh lp FileTransfer, trong trng hp ny ta dng cu t trong lp FileTransfer ny. Mt cu t l mt phng php c bit c cng tn nh ca lp. on m pha di ta s thy i tng objFileTransfer s c khi to bng cch gi cu t objFileTransfer = new FileTransfer(intChoice). public static String strFileName = "",strFilePath = "";

public static int intCheckChoice = 0; Hai bin thuc tnh strFileName v strFilePath s cha tn v ng dn ca file cn gi i. Bin intCheckChoice s gip cho ta xc nh my ang chy kiu server mode hay client mode trong qu trnh gi file. public static Socket clientSocket = null; public static ObjectOutputStream outToServer = null; public static ObjectInputStream inFromServer = null; Cc variable clientSocket, outToServer, inFromServer cng c khai bo, v cc tng ny c m t trn cc hnh v 1-8 trn. Lung outToServer c kiu l ObjectOutputStream l mt lung xut ca chng trnh; n c nh km vi socket. D liu m client gi n mng chy trong lung outToServer. Lung inFromServer c kiu l ObjectInputStream, l mt lung nhp n chng trnh; n c nh km vi socket. D liu n t network s chy vo lung inFromServer. public static void main (String [] args) throws IOException { BufferedReader stdin = new BufferedReader(new InputStreamReader (System.in)); System.out.println("\nSelect Type for this Computer:"); System.out.println(" 1. Connect to host (i.e This computer is a client)"); System.out.println(" 2. Wait for connections (i.e This computer is a server)"); System.out.println(); System.out.print("Please make a choice: "); System.out.flush(); int intChoice = Integer.parseInt(stdin.readLine()); on m s to nn mt i tng lung stdin c kiu l BufferedReader. Lung nhp ny s khi to vi System.in, gn lung ny vi cng c nhp chun (trong trng hp ny l bn phm). Nhng lnh ny cho php chng trnh c c k t nhp t bn phm, t gn vo bin intChoice chn kiu server mode hay client mode. if (intChoice == 1) { // This computer is a client System.out.print("Please type in the host address: "); System.out.flush(); strHostAddress = stdin.readLine(); System.out.print("Please type in the host port number: "); System.out.flush(); intPortNumber = Integer.parseInt(stdin.readLine()); } if (intChoice == 2) { //This computer is a server System.out.print("Give the port number to listen for requests: "); System.out.flush(); intPortNumber = Integer.parseInt(stdin.readLine()); System.out.print("Give the maximum number of clients for this server: ");

System.out.flush(); intMaxClients = Integer.parseInt(stdin.readLine()); } Nu intChoice bng 2 tc my chn kiu server mode, th ta s yu cu ngi dng chn s th t cng, chn s my client ti a c th kt ni n. Nu intChoice bng 1 tc my chn kiu client mode, th ta s yu cu ngi dng nhp vo a ch ca my server, nhp vo s th t cng giao tip vi server. Tt c cc gi tr ny sau c gn vo cc bin cn thit nh trong on m. objFileTransfer = new FileTransfer(intChoice); Dng m ny khi to mt i tng objFileTransfer bng cch dng cu t, l hm FileTransfer c cng tn vi lp.

public Label lblSelectFile; public Label lblTitle; public Label lblStudentName; public TextField tfFile; public Button btnBrowse; public Button btnSend; public Button btnReset; Ta tip tc khai bo cc thnh phn giao din ngi dng ho, n c m t trn hnh v.

public FileTransfer (int c) { setTitle("Java - File Transfer"); setSize(300 , 300); setLayout(null); addWindowListener(new WindowAdapter () { public void windowClosing (WindowEvent e) { System.exit(0); } } ); lblTitle = new Label("FILE TRANSFER BY IP"); add(lblTitle); lblTitle.setBounds(80,30,300,30); lblSelectFile = new Label("Select File:"); add(lblSelectFile); lblSelectFile.setBounds(15,87,100,20); lblStudentName = new Label("Thanh Thien - Thanh Tuan"); add(lblStudentName); lblStudentName.setBounds(130,270,200,20);

tfFile = new TextField(""); add(tfFile); tfFile.setBounds(13,114,200,20); btnBrowse = new Button("Browse"); btnBrowse.addActionListener(new buttonListener()); add(btnBrowse); btnBrowse.setBounds(223,113,50,20); btnSend = new Button("Send"); btnSend.addActionListener(new buttonListener()); add(btnSend); btnSend.setBounds(64,168,50,20); btnReset = new Button("Reset"); btnReset.addActionListener(new buttonListener()); add(btnReset); btnReset.setBounds(120,168,50,20); show(); Trng hp ny ta dng cu t khi to mt i tng, mt cu t khi to mt i tng ngay khi to. N trng tn vi lp, trong chng trnh ny nh ngha mt cu t ca lp tn FileTransfer. Trong phn u ca cu t n gin ta ch thit k giao din ngi dng, v d m lnh lblTitle = new Label("FILE TRANSFER BY IP") s gn ni dung cho n l FILE TRANSFER BY IP v sau lnh add(lblTitle) s a n ln Frame hin ti, cn cu lnh lblTitle.setBounds(80,30,300,30) c dng tng qut l setBounds(x,y,width,height) thit lp v tr v kch thc ca label ny. By gi ta hy set nhng cu m lnh sau: btnBrowse = new Button("Browse"); btnBrowse.addActionListener(new buttonListener()); add(btnBrowse); y l qu trnh iu qun s kin khi nhn button Browse. Mt EventListener lng ch mt s kin c th do i tng pht sinh. n lt n s gi cc phng php iu qun s kin, c tn l b iu qun s kin. Mt b lng ch s kin [event listener] cung cp cc phng php iu qun s kin ny. Lp thc thi b lng ch trong trng hp ny l lp buttonListener. Lp ny s c nh ngha phn sau ca m chng trnh. ================================================== ==================
2.3.2.2. Qu trnh nhn file (Receive file) Nhn file bn pha client

Tip theo y s l mt trong nhng phn quan trng ca chng trnh, phn ny m t qu trnh nhn file bn pha client if (c == 1) { // Client receives file intCheckChoice = 1; Bin c l s xc nh my tnh ang chy mode no, trong trng hp ny c=1 tc my ang chy mode client, ta gn cho bin intCheckChoice = 1 tip tc xc nh y l mode client trong trng hp nu c gi file t client. try { clientSocket = new Socket (strHostAddress,intPortNumber); outToServer = new ObjectOutputStream(clientSocket.getOutputStream()) ; outToServer.flush(); inFromServer = new ObjectInputStream(clientSocket.getInputStream()); Tip theo ta tin hnh to ra mt clientSocket t cc gi tr c sn strHostAddress v intPortNumber. Ta cng to ra hai lung outToServer v inFromServer nh cp u chng trnh, phng thc outToServer.flush() s x ht tt c nhng g cn trong lung outToServer ny ra ngoi.V y l qu trnh nhn file ti client (t server) nn ta s ch cn s dng lung inFromServer, lung ny n nhn nhng d liu t clientSocket bng phng thc clientSocket.getInputStream(). int intFlag = 0; while (true) { Object objRecieved = inFromServer.readObject(); Cn bin c intFlag gip ta thc hin vic x l d liu gi t server qua 3 giai on bng cch dng lnh switch. Cn i tng objRecieved c d liu t lung inFromServer. switch (intFlag) { case 0: if (objRecieved.equals("IsFileTransfered")) { intFlag++; } break; Giai on 1, chng trnh s kim tra iu kin objRecieved.equals("IsFileTransfered") bi v trong qu trnh gi file i t server, chng trnh bn server ghi vo i tng gi i mt chui "IsFileTransfered", qu trnh nhn client nu objRecieved.equals("IsFileTransfered") = true th ta bit chc rng d liu c gi i bng cng mt chng trnh bn server, ta kt thc giai on ny bng vic tng bin intFlag thm mt n v .

case 1: strFileName = (String) objRecieved; int intOption = JOptionPane.showConfirmDialog(this,clientSocket.ge tInetAddress().getHostName()+" is sending you "+strFileName+"!\nDo you want to recieve it?","Recieve Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUE STION_MESSAGE); if (intOption == JOptionPane.YES_OPTION) { intFlag++; } else { intFlag = 0; } break; Qua giai on 2, lc ny intFlag c gi tr l 1, ta ly ra t objRecieved mt gi tr kiu string cha tn file, tn file ny c thm vo objRecieved trong qu trnh gi file t server, lc ny mt hp thoi s hin ra bn pha server xc nhn rng ta c mun nhn file khng.

Nu ta chn Yes th intFlag s c tng thm mt n v na, cn ngc li th intFlag s tr v gi tr 0. case 2: byte[] arrByteOfReceivedFile = (byte[])objRecieved; FileOutputStream outToHardDisk = new FileOutputStream(strFileName); outToHardDisk.write(arrByteOfReceivedFile); intFlag = 0; JOptionPane.showMessageDialog(this,"File Recieved!","Confirmation",JOptionPane.INFORMATION_ MESSAGE); break; } Thread.yield(); } } catch (Exception e) {System.out.println(e);} } Qua n giai on 3, (intFlag lc ny bng 2) sau khi ta chn Yes th d liu ca file cha trong objRecieved s c c vo mng byte arrByteOfReceivedFile thng qua lnh byte[] arrByteOfReceivedFile = (byte[])objRecieved

Lung outToHardDisk sau s to ra mt file c tn trng vi tn file gi, d liu t arrByteOfReceivedFile s c chy vo lung ny. Nh vy lc ny y bn cng ca my client mi c to mt file ging c ni dung v tn ging ht nh file c gi t server, file ny c nm cng th mc vi file chng trnh. Chng trnh cng hin th mt hp thoi bo cho ta bit file c nhn. Cu m lnh Thread.yield() c tc dng khi m mt xu (thread) khng c vic g lm na, th n c th gi phng thc yield() ny bo cho b lp lch (scheduler) bit thc thi mt thread khc. Cn on m try ... catch c dng iu qun cc ngoi l (exception) hay cn gi l by li. Nhn file bn server By gi ta xt tip n trng hp nhn file bn server: if (c == 2) { // Server receives file vecConnectionSockets = new Vector(); intCheckChoice = 2; try { ServerSocket welcomeSocket = new ServerSocket(intPortNumber,intMaxClients); while (true) { vecConnectionSockets.addElement(new ThreadedConnectionSocket(welcomeSocket.accept())); Thread.yield(); } } catch (IOException ioe) {System.out.println(ioe);} } Nh ta bit th chng trnh bn server phi c nhim v to ra mt welcomeSocket trong qu trnh three-way handshake thc hin s to ra kt ni TCP gia my server v my client. welcomeSocket ny c to ra da vo hai gi tr intPortNumber v intMaxClients c gn gi tr trc . V cng ni t trc chng trnh ny bn server c kh nng ng thi transfer file vi nhiu my client nn nu ch to ra mt connectionSocket th khng nn ta phi ra mt Vector cc connectionSocket v ti u ho qu trnh thc thi th ta dng chc nng multithreading ca Java bng cch to s dng cc i tng ConnectionSocket dng c tch hp sn trong class ThreadedConnectionSocket. Cc i tng ca class ThreadedConnectionSocket c nh ngha l welcomeSocket.accept() v ni c a vo Vector thng qua phng thc addElement ca i tng Vector vecConnectionSockets. Sau y ta s tm hiu k v class ThreadedConnectionSocket mi c to thm. class ThreadedConnectionSocket extends Thread { public Socket connectionSocket; public ObjectInputStream inFromClient; public ObjectOutputStream outToClient;

Class ThreadedConnectionSocket ny l mt lp m rng ca lp Thread nn n c tnh nng a xu, cc thuc tnh ca lp ny bao gm mt connectionSocket v hai lung nh cp phn u l inFromClient v outToClient. public ThreadedConnectionSocket (Socket s) { connectionSocket = s; try { outToClient = new ObjectOutputStream(connectionSocket.getOutputStrea m()); outToClient.flush(); inFromClient = new ObjectInputStream(connectionSocket.getInputStream( )); } catch (Exception e) {System.out.println(e);} start(); } Ta cng nh ngha mt cu t trong lp ny, phng thc outToClient.flush() s x ht tt c nhng g cn trong lung outToClient ny ra ngoi. V y l qu trnh nhn file ti server (t client) nn ta s ch cn s dng lung inFromClient, lung ny n nhn nhng d liu t connectionSocket bng phng thc connectionSocket.getInputStream(). Chng trnh bt u thi hnh mt xu bng mt lnh gi phng php start() thuc v lp Thread. n lt phng php ny triu gi phng php run() nh ngha cng vic c thc hin. public void run () { try { int intFlag = 0; String strFileName = ""; while (true) { Object objRecieved = inFromClient.readObject(); switch (intFlag) { case 0: if (objRecieved.equals("IsFileTransfered")) { intFlag++; } break; case 1: strFileName = (String) objRecieved; int intOption = JOptionPane.showConfirmDialog(null,connectionSocke t.getInetAddress().getHostName()+" is sending you "+strFileName+"!\nDo you want to recieve it?","Recieve Confirm",JOptionPane.YES_NO_OPTION,JOptionPane.QUE STION_MESSAGE);

if (intOption == JOptionPane.YES_OPTION) { intFlag++; } else { intFlag = 0; } break; case 2: byte[] arrByteOfReceivedFile = (byte[])objRecieved; FileOutputStream outToHardDisk = new FileOutputStream(strFileName); outToHardDisk.write(arrByteOfReceivedFile); intFlag = 0; JOptionPane.showMessageDialog(null,"File Recieved!","Confirmation",JOptionPane.INFORMATION_ MESSAGE); break; } Thread.yield(); } } catch (Exception e) {System.out.println(e);} } } Nu quan st k th ta s thy cch x l ca n hon ton ging nh qu trnh nhn file bn client xt trn. Nhng dng m lnh trong phng php run() hon ton tng t nh qu trnh nhn file bn client, bin c intFlag gip ta thc hin vic x l d liu gi t client qua 3 giai on bng lnh switch. y ta s khng cn phn tch li ba giai on .. Nh vy cho n lc ny y ta phn tch xong mt cch chi tit qu trnh nhn file ti client t server v cng phn tch s ging nhau v khc nhau i vi qu trnh nhn file ti server t client (so vi nhn file ti client). phn k tip ta s i vo nghin cu qu trnh gi file ti client v qu trnh gi file ti server. ================================================== =========== 2.3.2.3. Qu trnh gi file (Send file) public static String showDialog () { FileDialog fd = new FileDialog(new Frame(),"Select File...",FileDialog.LOAD); fd.show(); return fd.getDirectory()+fd.getFile(); } y l mt hm nh gip cho ta c th chn c file cng vi ng dn ca mt file thng qua

mt hp thoi quen thuc. Kt qu tr v s l tn th mc + tn file chn. Hm ny s c dng on m sau ca chng trnh. Nh cp phn trc, th mt EventListener lng ch mt s kin c th do i tng pht sinh. n lt n s gi cc phng php iu qun s kin, c tn l b iu qun s kin. Mt b lng ch s kin [event listener] cung cp cc phng php iu qun s kin ny. Lp thc thi b lng ch trong trng hp ny l lp buttonListener. private class buttonListener implements ActionListener {

public void actionPerformed (ActionEvent ae) { byte[] arrByteOfSentFile = null; if (ae.getSource() == btnBrowse) { strFilePath = showDialog(); tfFile.setText(strFilePath); int intIndex = strFilePath.lastIndexOf("\\"); strFileName = strFilePath.substring(intIndex+1); } Nh ta thy trong on m ny th khi ngi dng click vo button Browse (ae.getSource() == btnBrowse) th chng trnh s gi hm showDialog() c nh ngha trc, hm ny s tr vo bin strFilePath tn v ng dn y ca mt file c chn, sau ta li hin th gi tr ny ln TextField tfFile, sau bng mt vi hm x l chui th ta ly c gi tr tn file v gn vo bin strFileName. Bin strFileName ny ch cha tn file (v d l TestTransferFile.txt) m khng h c cha ng dn th mc. phn k tip ta s xt phn quan trng ca chng trnh, l phn send file (khi ngi dng nhn button Send) if (ae.getSource() == btnSend) { try { FileInputStream inFromHardDisk = new FileInputStream (strFilePath); int size = inFromHardDisk.available(); arrByteOfSentFile = new byte[size]; inFromHardDisk.read(arrByteOfSentFile,0,size); Chng trnh s to ra mt lung nhp c tn inFromHardDisk c kiu l FileInputStream, n lin kt vi file vi ng dn nm trong bin strFilePath, bin size s xc nh c s byte c th c c m khng b phong to. Cu lnh inFromHardDisk.read(arrByteOfSentFile,0,size) s c d liu t strFilePath v ghi vo mng arrByteOfSentFile. Gi file bn server

if (intCheckChoice == 2) {// Send file from server for (int i=0;i<vecConnectionSockets.size();i++) { ThreadedConnectionSocket tempConnectionSocket = (ThreadedConnectionSocket)vecConnectionSockets.ele mentAt(i); tempConnectionSocket.outToClient.writeObject("IsFi leTransfered"); tempConnectionSocket.outToClient.flush(); tempConnectionSocket.outToClient.writeObject(strFi leName); tempConnectionSocket.outToClient.flush(); tempConnectionSocket.outToClient.writeObject(arrBy teOfSentFile ); tempConnectionSocket.outToClient.flush(); } } intCheckChoice bng 2, tc ta ang xt trng hp gi file t server i, v server c th gi file cho nhiu client nn ta, phi to mt vng lp for vi s ln lp bng s client kt ni n server, gi tr ny chnh l bng vecConnectionSockets.size(). Trong mi ln lp th ta tin hnh send file bng cc bc nh sau: - Khi to mt tempConnectionSocket thuc class ThreadedConnectionSocket to trc . - Ghi vo i tng ny mt chui "IsFileTransfered" gip xc nhn li file bn nhn. - a d liu t mng byte arrByteOfSentFile (mng ang cha d liu ca file cn gi) vo i tng tempConnectionSocket a d liu ra socket. - ng vi mi bc th ta dng phng thc flush( ) ghi ra d liu ca lung, iu ny bo m rng tt c d liu nm nhng lung di c gi i. Gi file bn client if (intCheckChoice == 1) { // Send file from client outToServer.writeObject("IsFileTransfered"); outToServer.flush(); outToServer.writeObject(strFileName); outToServer.flush(); outToServer.writeObject(arrByteOfSentFile); outToServer.flush(); } intCheckChoice bng 1, tc ta ang xt trng hp gi file t client i, mi client ch c th kt ni n mt server nn ta dng lung outToServer khai bo trc t u chng trnh. y cng xin nhc li l lung outToServer c kiu l ObjectOutputStream l mt lung xut ca chng trnh; n c nh km vi clientSocket. D liu m client gi n mng chy trong lung outToServer. Ta thc hin qua cc bc cng tng t nh bn server. - Ghi vo lung ny mt chui "IsFileTransfered" gip xc nhn li file bn nhn - a d liu t mng byte arrByteOfSentFile (mng ang cha d liu ca file cn gi) vo lung

outToServer, lung ny c gn vi clientSocket. - ng vi mi bc th ta dng phng thc flush( ) ghi ra d liu ca lung, iu ny bo m rng tt cu d liu nm nhng lung di c gi i. JOptionPane.showMessageDialog(null,"File Sent!","Confirmation",JOptionPane.INFORMATION_MESS AGE); Sau khi gi d liu ra socket thnh cng th ta hin mt hp thoi thng bo File c gi i. if (ae.getSource() == btnReset) { tfFile.setText(""); } Cn trong trng hp ngi dng nhn button Reset th chng trnh ch xo trng TextField tfFile v ch i ngi dng thao tc li t u. 1.2.4. Nhn xt Nh vy ta va phn tch xong tng chc nng, t dng m mt trong chng trnh giao nhn file bng IP. Ta hy nh li rng TCP cung cp dch v giao nhn d liu ng tin. iu ny c ngha rng, nu file trong qu trnh giao nhn file trong mng b h hng th giao thc TCP s tin hnh giao nhn li file, bo m rng d liu lun c phn phi chnh xc. S giao nhn tr li ny hon ton n giu i vi chng trnh ng dng, tc l ngi lp trnh khng cn phi quan tm n s truyn nhn file tr li (retransmission) ny. kim tra chng trnh ny th ta phi dch file FileTransfer.java (hay chp nhng file bin dch) c bn server ln client. Ta cng phi chy chng trnh my chy server mode trc. iu ny s to ra mt process bn server ch i s giao tip t pha my chy client mode. Sau ta chy chng trnh client mode my client, ta phi bo m rng phi bao gm ng tn a ch ca server (host address), v phi chn ng s th t cng thit lp sn bn server. Trong mt vi trng hp him gp th chng trnh s khng giao nhn file c do b firewall, v th ta phi bo m rng cng m ta chn khng b block bi firewall. Sau khi chy xong client mode th chng trnh s to ra mt process client v thit lp mt TCP connnection gia my chy mode server v my chy mode client. Cui cng, giao nhn file th ta ch vic chn file trong cng v nhn Send gi i. ================================================== ======== 1.3. Chng trnh 2: Giao nhn x l chui 1.3.1. Cch thc hot ng Chng trnh ny c c im nh sau: 1. Mt my khch c mt dng ch t cng c nhp chun (bn phm) v gi dng ny ra socket ca n v t n c gi n server 2. Mt my ch c mt dng ch t connection socket ca n 3. My ch s thc hin vic o ngc chui (dng) .

4. My ch s gi dng ch thay i ra connection socket ca n v t dng ch s c gi qua my khch 5. My khch c dng ch thay i t socket ca n v in dng ch ra mn hnh. Chng trnh my client c tn l EchoClient.java, v chng trnh my ch c tn l EchoServer.java. Mt khi c hai chng trnh c bin dch host tng ng, chng trnh bn server phi c thc thi trc bn server, n s to ra mt process ti server. Nh cp nhng phn trn, tin trnh (process) my ch s ch i cho n khi c s giao tip ca tin trnh my khch. Khi chng trnh my khch c thc thi, mt tin trnh c to ra my khch, v tin trnh ny s tip xc vi my ch v thit lp mt TCP connection vi n. Ngi dng ti my khch lc ny y c th s dng ng dng ny gi tng dng v nhn v dng ch o ngc. 1.3.2. EchoClient.java Cng tng t nh chng trnh 1 giao nhn file th y, chng trnh EchoClient to ra 3 lung v mt socket nh c m t hnh bn di Socket th c gi l clientSocket. Cn lung (stream) inFromUser c kiu l BufferedReader, l mt lung nhp n chng trnh; n c nh km b nhp chun, trong trng hp ny l bn phm. Khi ngi s dng g k t vo bn phm my tnh, dng k t ny s chy vo lung inFromUser. Lung inFromServer l mt lung nhp khc ca chng trnh; n c gn vo socket. Nhng k t n t mng (network) s chy vo lung inFromServer. Cui cng, lung outToServer l mt lung xut ca chng trnh ca chng trnh; n cng c gn vo socket. Nhng k t m my khch gi n mng s chy vo lung outToServer. Phn ghi ch v gii thch c ghi km trong m ngun ca chng trnh Code: import java.net.*; import java.io.*; public class EchoClient { public static void main(String args[]){ if (args.length !=1){ System.out.println("Usage: java EchoClient <serverAddr>"); return; } // To i tng lin kt vi my ch (thc t ch l lin kt vi clientSocket) ClientConnect client = new ClientConnect(args[0],3456);

// Nhn d liu t bn phm v gi n my ch x l client.requestServer(); // Ct t kt ni vi i tng lin kt client.shutdown(); } } // Thit k lp lin kt vi my ch thng qua socket v nhn d liu t bn phm class ClientConnect { // Lu gi i tng kt ni Socket clientSocket; // Lung dng gi d liu n clientSocket DataOutputStream outToServer; // Lung dng c d liu do my ch gi v BufferedReader inFromServer; /* Phng thc khi dng to kt ni vi my ch theo a ch destination v cng port */ public ClientConnect(String destination,int port){ try{ // To socket kt ni pha client clientSocket = new Socket(destination,port); // Ly vo lung nhp dng c d liu do my ch gi v inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); // Ly v lung xut dng gi d liu n socket t chuyn n my ch outToServer= new DataOutputStream( clientSocket.getOutputStream()); System.out.println("Connected to server at port 3456."); } catch (Exception e) { // Nu gp li th in li ra mn hnh System.out.println(e); } }

/* Phng thc ny s nhn chui d liu t bn phm v gi n my ch x l */ public void requestServer(){ // To lung c d liu t bn phm BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); boolean finished=false; do { try{ // To menu la chn. S: gi d liu, R: nhn d liu, Q: chm dt System.out.print("Send, receive, or quit (S/R/Q): "); System.out.flush(); String line = inFromUser.readLine(); if(line.length()>0){ line=line.toUpperCase(); switch (line.charAt(0)){ // Nu ngi dng chn S, d liu nhp vo s c gi n clientSocket, t chuyn qua my ch case 'S': String sendLine = inFromUser.readLine(); outToServer.writeBytes(sendLine); outToServer.write(13); outToServer.write(10); outToServer.flush(); break; // Nu ngi dng chn R, d liu do my ch x l s c nhn v v in ra case 'R': int inByte; System.out.print(">>>>"); while ((inByte = inFromServer.read()) != '\n') System.out.write(inByte); System.out.println(); break; // Nu ngi dng chn Q, chng trnh s chm dt case 'Q':

finished=true; break; default: break; } } }catch (Exception e){ // Nu li xut nhp th in li ra mn hnh System.out.println(e); } } while(!finished); } /* Phng thc ny c dng ng kt ni t my khch vi my ch */ public void shutdown(){ try{ clientSocket.close(); }catch (IOException ex){ System.out.println("IO error closing socket"); } } } 1.3.3. EchoServer.java Chng trnh EchoServer cng c gii thch tng t nh chng trnh EchoClient. Phn ghi ch v gii thch c ghi km trong m ngun ca chng trnh Code: import java.net.*; import java.io.*; public class EchoServer { public static void main(String args[]){ try{ /* To i tng ServerSocket dng lng nghe kt ni t cc my khch gi n cng 3456 */ ServerSocket welcomeSocket = new ServerSocket(3456);

int localPort = welcomeSocket.getLocalPort(); System.out.println("Echo Server is listening on port "+localPort+"."); //Ch i kt ni t my khch /* Lu : n y chng trnh s dng li v ch i cho n khi c kt ni xy ra */ Socket connectionSocket = welcomeSocket.accept(); /* C kt ni xy ra. Ly cc thng tin t my khch v cho in ra mn hnh */ String destName = connectionSocket.getInetAddress().getHostName(); int destPort = connectionSocket.getPort(); System.out.println("Accepted connection to "+destName +" on port "+destPort+"."); //Ly v lung nhp c d liu t connectionSocket, do my khch gi n /* Lu : Ta a lung nhp vo b lc lung chuyn i thnh lung BufferReader c kh nng c c mt chui k t bng phng thc readLine() */ BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream( ))); // Ly v lung xut ghi d liu vo connectionSocket, t chuyn n my khch DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream( )); // Ch c vo x l d liu do my khch gi n boolean finished = false; do { // c mt chui k t t connectionSocket do my khch gi n String inLine = inFromClient.readLine(); // In chui nhn c ra mn hnh System.out.println("Received: "+inLine); // So snh chui gi n. Nu l quit th chm dt if(inLine.equalsIgnoreCase("quit")) finished=true; // X l o ngc chui

String outLine=new EchoString(inLine.trim()).getString(); // Gi tr kt qu v connectionSocket t tr v my khch for(int i=0;i<outLine.length();++i) outToClient.write((byte)outLine.charAt(i)); outToClient.write(13); outToClient.write(10); outToClient.flush(); System.out.println("Sent: "+outLine); } while(!finished); // ng lung v cc kt ni inFromClient.close(); outToClient.close(); connectionSocket.close(); welcomeSocket.close(); }catch (IOException e){ // Nu c li th in ra mn hnh System.out.println(e); } } } //Lp ny dng x l v o ngc ni dung ca mt chui class EchoString { String s; public EchoString(String in){ int len = in.length(); char outChars[] = new char[len]; //o ngc k t t trc ra sau for(int i=0;i<len;++i) outChars[len-1-i]=in.charAt(i); s = String.valueOf(outChars); } public String getString(){ return s;

} } 1.3.4. Kt qu V sau y l qu trnh trao i gia my khch v my ch: My khch My ch Send, receive, or quit (S/R/Q): SHello Server !Send, receive, or quit (S/R/Q): R>>>>! revreS olleH Received: Hello Server !Sent: ! revreS olleH Send, receive, or quit (S/R/Q): s123456789Send, receive, or quit (S/R/Q): r>>>>987654321 Received: 123456789Sent: 987654321 Send, receive, or quit (S/R/Q): SHow are you?Send, receive, or quit (S/R/Q): r>>>>?uoy era woH Received: How are you?Sent: ?uoy era woH Send, receive, or quit (S/R/Q): q

1.4. Ti liu tham kho: 1. Gio trnh Lp trnh Hng i tng JAVA - Ngc Anh Th Press - NXB Thng K 2. Computer Networking - By James F. Kurose and Keith W. Ross - Addison Wesley 3. Website http://www.planet-source-code.com 4. JAVA Lp trnh mng - Nguyn Phng Lan v Hong c Hi - NXB Gio Dc (su tm)

You might also like