tut lap trinh tcp socket

Upload: do-cong-thanh

Post on 03-Apr-2018

227 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 TUT Lap Trinh TCP Socket

    1/30

    [TUT]JAVA: Lp trnh TCP Socket

    Quote:

    JAVA: Lp trnh Socket vi TCPNgi son: Nimbus

    Ti liu tham kho:1. Gio trnh Lp trnh Hng i tng JAVA -Ngc Anh Th Press -NXB Thng K2. Computer Networking - By James F. Kurose and Keith W. Ross - Addison Wesley

    3. Websitehttp://www.planet-source-code.com4. JAVA Lp trnh mng -Nguyn Phng Lan v Hong c Hi -NXB Gio Dc 1.1. Lptrnh Socket vi TCP

    1.1.1. Gii thiuTrong phnny 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 (clientprogram) 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 nhaubng cch c t v ghi n nhng socket. Khi to ra mt ng dng mng, nhim v ca chngta 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 hinthc 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 vinhng quy tc c nu ra trong RFC. V d, mt chng trnh my khch c th hin thcmt chng trnh FTP client, c nh ngha trong [RFC 959], v chng trnh my ch thhin 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 ngdng ny th chng trnh my khch ln my ch u khng cn phi ph hp vi bt c RFCno. Mt nh pht trin n l c th to ra c hai chng trnh client v server, v nh pht trinny hon ton iu khin tt c nhng g c trong m lp trnh. Nhng bi v m lp trnh khngc hin thc trn giao thc chun, nnnhng nh pht trin c lp khc s khng th nopht 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 nghatrong cc RFC.Trong phn k tip ta s nghin cu nhng im mu cht pht trin mt ng dng client-server gi c quyn. Trong qu trnh pht trin, mt trong nhng quyt nh quan trng m nhpht 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 lius c truyn gia hai h thng cui. UDP l mt giao thc khng kt ni v gi i nhng gid liu c lp t h thng cui ny n nhng h thng cn li, m khng h bo m d liuc c nhn hay khng. Trong khun kh bi tp ny th ta ch nghin cu mt ng dng nhchy 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 mhn, v mi dng c th d dng gii thch vi c nhng ngi lp trnh mi bt u. Th hai,

    http://thuviendientu.org/http://www.planet-source-code.com/http://www.planet-source-code.com/http://www.planet-source-code.com/http://www.planet-source-code.com/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    2/30

    nhng chng trnh client-server lp trnh bng Java gia tng ngy cng thng dng, v n cth tr thnh tiu chun cho lp trnh mng trong vi nm ti. Java l mt ngn ng c lp nntng, n c c ch by li (iu qun cc ngoi l) cng trng m c th gii quyt hu n ccli 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 bngcch gi nhng thng ip n socket. Chng ta c th ni mt cch n gin rng mi mt tintrnh 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 (ApplicationProcess) v TCP. Nhng nh pht trin ng dng c th kim sot mi th bn pha lpApplication 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. Mykhch 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 khimy khch tin hnh s giao tip u tin. Th hai, chng trnh bn server phi c sn mt scng (port) c th tip n (welcome) nhng giao tip khi to t bn pha client. S dng stng t nh cn nh/cnh ca i vi process/socket nh ni trn th ta c th xem nh skhi 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 mtTCP connection. iu ny c thc bn chng trnh my client bng cch to ra mt itng socket (ta gi n l clientSocket). Khi mt my khch to ra mt i tng socket th ns 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 viserver. Three-way handshake ny th hon ton n giu vi c chng trnh server ln chngtrnh client.Trong sut qu trnh three-way handshake, tin trnh bn my khch s g vo cng ca tintrnh my ch. Khi server nhn c s g ca ny, n s to ra mt cnh ca mi (tht ra l mtsocket mi) m phc v cho tng client chuyn bit. Trong bi tp ny, cnh ca cho nchnh l mt i tng ServerSocket m ta gi l welcomeSocket. Khi mt my khch gca, chng trnh s vin dn phng thc accept() ca welcomeSocket, phng thc ny s tora mt socket khc cho client. Vo cui qu trnh handshaking ny th mt kt ni TCP s cthit lp gia socket ca client v mt socket mi ca server. T y tr v sau, ta s gi newsocket ny bng tn gi l connection socket

    TCP connection uc xem nh l mt ng dn o gia clients socket v server's connectionsocket. Lc ny, tin trnh bn my khch c th gi nhng byte tu n socket ca n, TCPbo 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 nv tin trnh bn server cng c th gi byte n connection socket ca n. iu ny c m t hnh bn di.

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    3/30

    Bi v socket ng mt vai tr quan trng trong nhng ng dng client-server, cho nn nhngng dng client-server thng c gi l socket programming. Trc khi i n ng dng bitp 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 tintrnh (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 nhngngun vo ca mt tin trnh, v d nh l mt cng c nhp chun (keyboard) hoc mt socketm d liu i vo n t network. Nu mt lung l lung xut, th n s c nh km vi mtvi ngun xut ca tin trnh, v d nh l mt cng c xut chun (mn hnh) hoc mt socketm i ra t n d liu s i vo network.

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

    1.2. Chng trnh v d 1: Giao nhn file bng IP1.2.1. Cch thc hot ngChng 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 javaFileTransfer. Tip theo chng trnh s yu cu ngi dng chn la computer tr thnhclient hoc server, c th hin nh trn hnh v. Ta nhp vo 1 nu chn l client v nhpvo 2 nu mun my tnh tr thnh server.

    Chy chng trnh server modeTu chn 2 phi c chn trc my tnh c ch nh chy server mode, sau mytnh ny s ch i cc kt ni n n. Ta phi nhp tip port number, ng vi server mode nyth ta c th chn bt c port number no ln hn 1024, v nhng port number di 1024 bgi trc v s dng bi h thng (well-known ports). Chng trnh ny cng c th thc hingiao nhn file gia mt server v nhiu my con ng thi trong mt h thng mng nn n syu cu ta nhp vo s lng my client ln nht c th kt ni n server ny.

    Chy chng trnh client modeTng 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 hptrn hnh bn di th tn my chy server mode c a ch IP trong mng LAN l192.168.0.144). Tip tc ta s nhp port number, client phi cng ng chn nhp port numbernh bn server nh bn server chn th mi c th giao nhn file c.

    Giao din giao nhn fileSao 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 hingi dng c chp nhn nhn file hay khng. Theo m t trn hnh v th mysieutoc.mshome.net (my chy server mode c a ch IP 192.168.0.144 nh hnh trn) gimt file c tn l TestTransferFile.txt cho my khc.

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    4/30

    Sau khi chnnhn file xong th chng trnh s tip tc hin mt hp thoi khc na thngbo rng file c gi hay c nhn. File sau khi nhn s c cha trong cng th mccha 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());

    http://thuviendientu.org/http://www.planet-source-code.com/http://www.planet-source-code.com/http://www.planet-source-code.com/http://www.planet-source-code.com/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    5/30

    if (intChoice == 1) { // This computer is a clientSystem.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);

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    6/30

    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 fileintCheckChoice = 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:

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    7/30

    if (objRecieved.equals("IsFileTransfered")) {

    intFlag++;

    }break;

    case 1:

    strFileName = (String) objRecieved;int intOption = JOptionPane.showConfirmDialog(this,clientSocket.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(this,"FileRecieved!","Confirmation",JOptionPane.INFORMATION_ MESSAGE);

    break;

    }

    Thread.yield();}

    } catch (Exception e) {System.out.println(e);}

    }

    if (c == 2) { // Server receives filevecConnectionSockets = 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);}}

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    8/30

    }

    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

  • 7/28/2019 TUT Lap Trinh TCP Socket

    9/30

    }

    if (intCheckChoice == 1) { // Send file from clientoutToServer.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 () {

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    10/30

    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 recieveit?","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);}}

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    11/30

    }

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

    1.2.3. Gii thch phn hin thc chng trnhChng ta s nghin cu chi tit, tng dngmt 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 trongchng trnh

    1.2.3.1 Nhng im mu cht ca chng trnhTi my chy client modeChng 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 nhkm 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. Dliu m client gi n mng chy trong lung outToServer.

    Xt qu trnh nhn File: Lung inFromServer c kiu l ObjectInputStream, l mt lung nhpn chng trnh; n c nh km vi socket. D liu n t network s chy vo lunginFromServer. Cn lung outToHardDisk c kiu l FileOutputStream, l lung xut ca chngtrnh; n c nh km vi cng, d liu t lung inFromServer s i vo lungoutToHardDisk, t n s ghi file ra cng my tnh

    Ti my chy server modeChng 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 lunginFromHardDisk, outToHardDisk, inFromClient, outToClient v connectionSocket c biudin 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 vnhiu my con ng thi trong mt h thng mng nn ti u ho qu trnh hot ng th takhai bo thm mt lp na gi l ThreadedConnectionSocket, lp ny nh ngha mt i tngsocket cng tng t nh connectionSocket m t trn nhng lp ny l lp m rng calp Thread, iu ny s tn dng c tnh nng a xu (multithreading) ca Java. V nhngThreadedConnectionSocket li c a vo lp Vector. Kt qu l ta c th giao nhn file giamt 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 trnh2.3.2.1. Qu trnh khai bo v to i tng

    import java.io.*;

    import java.net.*;

    import java.util.*;

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    12/30

    java.io v java.net l nhng gi trong Java. Gi java.io cha cc lp cho cc lung xut v lungnhp. C th l, gi java.io cha cc lp ObjectOutputStream, ObjectInputStream,FileInputStream, FileOutputStream, nhng lp ny c sdng v m t trn. Cn gijava.net th cung cp nhng lp h tr mng. C th l, n cha cc lp Socket vServerSocket. 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 chnht m ta s da vo n. Trong chng trnh nyta 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 giaodin hnh nh d lm vic. Mt thnh phn GUI l mt i tng hnh nh m ngi dngtng 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 cchnh ng ny to ra mt s kin. C mt s s kin cn c chng trnh iu qun mt cchr rt, ta s phn tch k iu ny khi i vo tng dng m c th. Cn Swing chnh l mt s bsung 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, lpny lp m rng ca lp Frame. Mt Frame l mt ca s c lp. Cc khung thng cdng trong cc ng dng yu cu giao din ngi dng ho. Tip theo ta khai bo cc binthuc 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 akt ni n server cc bin ny s c gn t pha ngi dng. Cn vecConnectionSockets lmt Vector cha cc ThreadedConnectionSocket h tr cho vic nhiu my client kt ni nmt my ch nh bn trn. Trong trng hp ny ta dng kiu Vector v lp Java Vectorcung cp mt dng mng chnh c c c th tng trng khi c thm mt phn t c bsung 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 tnnh ca lp. on m pha di ta s thy i tng objFileTransfer sc khi to bngcch gi cu t objFileTransfer = new FileTransfer(intChoice).

    public static String strFileName = "",strFilePath = "";

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    13/30

    public static int intCheckChoice = 0;

    Hai bin thuc tnh strFileName v strFilePath s cha tn v ng dn ca file cn gi i. BinintCheckChoice s gip cho ta xc nh my ang chy kiu server mode hay client mode trongqu 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 lmt lung xut ca chng trnh; n c nh km vi socket. D liu m client gi n mngchy trong lung outToServer. Lung inFromServer c kiu l ObjectInputStream, l mt lungnhp n chng trnh; n c nh km vi socket. D liu n t network s chy vo lunginFromServer.

    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 skhi to vi System.in, gn lung ny vi cng c nhp chun (trong trng hp ny l bnphm). Nhng lnh ny cho php chng trnh c c k t nhp t bn phm, t gn vobin 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 serverSystem.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: ");

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    14/30

    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 kiuclient mode, th ta s yu cu ngi dng nhp vo a ch ca my server, nhp vo s th tcng giao tip vi server. Tt c cc gi tr ny sau c gn vo cc bin cn thit nhtrong on m.

    objFileTransfer = new FileTransfer(intChoice);

    Dng m ny khito mt i tng objFileTransfer bng cch dng cu t, l hm FileTransferc 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);

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    15/30

    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 tngngay khi to. N trng tn vi lp, trong chng trnh ny nh ngha mt cu t ca lp tnFileTransfer. Trong phn u ca cu t n gin ta ch thit k giao din ngi dng, v d mlnh lblTitle = new Label("FILE TRANSFER BY IP") s gn ni dung cho n l FILETRANSFER BY IP v sau lnh add(lblTitle) s a n ln Frame hin ti, cn cu lnhlblTitle.setBounds(80,30,300,30) c dng tng qut l setBounds(x,y,width,height) thit lp vtr 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 skin c th do i tng pht sinh. n lt n s gi cc phng php iu qun s kin, c tnl 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. Lpny 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

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    16/30

    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 sxc 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 tserver 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 tserver, 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 .

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    17/30

    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 sc 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 sc c vo mng byte arrByteOfReceivedFile thng qua lnh byte[]

    arrByteOfReceivedFile = (byte[])objRecieved

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    18/30

    Lung outToHardDisk sau s to ra mt file c tn trng vi tn file gi, d liu t

    arrByteOfReceivedFile sc 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 tserver, 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 cth 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 trintPortNumber v intMaxClients c gn gi tr

    trc . V cng ni ttrc chng trnh ny bn server c khnng 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;

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    19/30

    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);

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    20/30

    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 tnh qu trnh nhn file bn

    client, bin c intFlag gip ta thc hin vic x l d liu gi tclient 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 ktip ta si 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 thchn c file cng vi ng dn ca mt file thng qua

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    21/30

    mt hp thoi quen thuc. Kt qu tr v sl tn th mc + tn file chn. Hm ny sc dng

    on m sau ca chng trnh.

    Nh cp phn trc, th mt EventListener lng ch mt s kin c thdo i tng pht

    sinh. n lt n s gi cc phng php iu qun s kin, c tn l biu 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 chtrong 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 ktip 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 sxc nh c s byte c thc c m

    khng b phong to. Cu lnh inFromHardDisk.read(arrByteOfSentFile,0,size) sc d liu t

    strFilePath v ghi vo mng arrByteOfSentFile.

    Gi file bn server

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    22/30

    if (intCheckChoice == 2) {// Send file from server

    for (int i=0;i

  • 7/28/2019 TUT Lap Trinh TCP Socket

    23/30

    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

    chi ngi dng thao tc li tu.

    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 bh 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 tonn 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 chi 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 thta 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 chc mt dng ch t connection socket ca n

    3. My ch s thc hin vic o ngc chui (dng) .

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    24/30

    4. My ch s gi dng ch thay i ra connection socket ca n v t dng ch sc 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 chai 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 chi 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 tnh chng trnh 1 giao nhn file th y, chng trnh EchoClient to ra 3 lung v

    mt socket nh c m thnh 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 tn 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 ");

    return;

    }

    // To i tng lin kt vi my ch (thc tch l lin kt vi clientSocket)

    ClientConnect client = new ClientConnect(args[0],3456);

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    25/30

    // 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 klp lin kt vi my ch thng qua socket v nhn d liu t bn phm

    class ClientConnect {

    // Lu gii 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 chtheo 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);

    }

    }

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    26/30

    /*

    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 phmBufferedReader 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 sc 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 sc 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':

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    27/30

    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 tnh 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);

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    28/30

    int localPort = welcomeSocket.getLocalPort();

    System.out.println("Echo Server is listening on port "+localPort+".");

    //Chi kt ni t my khch

    /*

    Lu : n y chng trnh s dng li v chi 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 khnng 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( ));

    // Chc 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;

    // Xl o ngc chui

    http://thuviendientu.org/http://thuviendientu.org/
  • 7/28/2019 TUT Lap Trinh TCP Socket

    29/30

    String outLine=new EchoString(inLine.trim()).getString();

    // Gi tr kt qu v connectionSocket t tr v my khch

    for(int i=0;i

  • 7/28/2019 TUT Lap Trinh TCP Socket

    30/30

    }

    }

    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. Websitehttp://www.planet-source-code.com

    4. JAVA Lp trnh mng - Nguyn Phng Lan v Hong c Hi - NXB Gio Dc

    (su tm)

    http://thuviendientu.org/http://www.planet-source-code.com/http://www.planet-source-code.com/http://www.planet-source-code.com/http://www.planet-source-code.com/http://thuviendientu.org/