Transcript
  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    1/34

    TRNG I HC BCH KHOA

    KHOA CNG NGH THNG TIN

    B MN MNG V TRUYN THNG

    BO COTHC HNH LP TRNH MNG

    SV thc hin : Trn Anh TunLp : 06T3Nhm : 08AGV hng dn : Nguyn Vn Nguyn

    Nng 2011

    MC LC

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    2/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    CHNG 1. C S L THUYT ........................................................................41.1. MHNHCLIENT-SERVER: ..................................................................................51.2. GIAOTHC TCP ..............................................................................................61.3. GIAOTHC UDP: ............................................................................................6

    CHNG 2. THIT K V XY DNG CHNG TRNH ...........................72.1. LAB1 ............................................................................................................7

    2.1.1. Net1 .....................................................................................................72.1.2. Student Manager .................................................................................92.1.3. NumberTCPSimple ...........................................................................12

    2.2. LAB2 ..........................................................................................................172.2.1. Net1 ...................................................................................................172.2.2. Net2 ...................................................................................................182.2.3. Net3 ...................................................................................................202.2.4. Net4 ...................................................................................................21

    2.2.5. KnockKnock .....................................................................................222.3. LAB3 ..........................................................................................................272.3.1. MulticastPeer ....................................................................................272.3.2. Multicast ............................................................................................29

    CHNG 3. KT LUN V HNG PHT TRIN .....................................34

    Chng 1. C S L THUYT

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 4

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    3/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    1.1. M hnh client-server:M hnh client/server nh sau: Client/Server l m hnh tng qut nht, trn thc t

    th mt server c th c ni ti nhiu server khc nhm lm vic hiu qu v nhanhhn. Khi nhn c 1 yu cu t client, server ny c th gi tip yu cu va nhn

    c cho server khc v d nh database server v bn thn n khng th x l yu cuny c. My server c th thi hnh cc nhim v n gin hoc phc tp. V d nhmt my ch tr li thi gian hin ti trong ngy, khi mt my client yu cu ly thngtin v thi gian n s phi gi mt yu cu theo mt tiu chun do server nh ra, nuyu cu c chp nhn th my server s tr v thng tin m client yu cu. C rtnhiu cc dch v server trn mng nhng n u hot ng theo nguyn l l nhn ccyu cu t client sau x l v tr kt qu cho client yu cu. Thng thng chngtrnh server v client c thi hnh trn hai my khc nhau. Cho d lc no server cng trng thi sn sng ch nhn yu cu t client nhng trn thc t mt tin trnh lintc qua li (interaction) gia client v server li bt u pha client, khi m client gi

    tn hiu yu cu ti server. Cc chng trnh server thng u thi hnh mc ngdng (tng ng dng ca mng). S thun li ca phng php ny l n c th lmvic trn bt c mt mng my tnh no c h tr giao thc truyn thng chun c th y l giao thc TCP/IP. Vi cc giao thc chun ny cng gip cho cc nh sn xutc th tch hp nhiu sn phm khc nhau ca h ln mng m khng gp phi khkhn g. Vi cc chun ny th cc chng trnh server cho mt dch v no y c ththi hnh trn mt h thng chia s thi gian (timesharing system) vi nhiu chngtrnh v dch v khc hoc n c th chy trn chnh mt my tnh cc nhn bnhthng. C th c nhiu chng server cng lm mt dch v, chng c th nm trnnhiu my tnh hoc mt my tnh. Vi m hnh trn chng ta nhn thy rng m hnh

    client/server ch mang c im ca phn mm khng lin quan g n phn cng mcd trn thc t yu cu cho mt my server l cao hn nhiu so vi my client. L do l

    bi v my server phi qun l rt nhiu cc yu cu t cc clients khc nhau trn mng.u v nhc im chnh C th ni rng vi m hnh client/server th mi th dngnh u nm trn bn ca ngi s dng, n c th truy cp d liu t xa (bao gm cccng vic nh gi v nhn file, tm kim thng tin, ...) vi nhiu dch v a dng m mhnh c khng th lm c. M hnh client/server cung cp mt nn tng l tng cho

    php tch hp cc k thut hin i nh m hnh thit k hng i tng, h chuyngia, h thng tin a l (GIS) ... Mt trong nhng vn ny sinh trong m hnh ny l tnh an ton v bo mt thng tin trn mng. Do phi trao i d liu gia 2 my 2khu vc khc nhau cho nn d dng xy ra hin tng thng tin truyn trn mng b l.

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 5

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    4/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    1.2. Giao thc TCP

    - B giao thc TCP/IP, ngn gn l TCP/IP (ting Anh: Internet protocol

    suite hoc IP suite hoc TCP/IP protocol suite - b giao thc lin mng), l mt b

    cc giao thc truyn thng ci t chng giao thc m Internet v hu ht cc mngmy tnh thng mi ang chy trn . B giao thc ny c t tn theo hai giao

    thc chnh ca n l TCP (Giao thc iu khin Giao vn) v IP (Giao thc Lin

    mng). Chng cng l hai giao thc u tin c nh ngha.

    - Nh nhiu b giao thc khc, b giao thc TCP/IP c th c coi l mt

    tp hp cc tng, mi tng gii quyt mt tp cc vn c lin quan n vic truyn

    d liu, v cung cp cho cc giao thc tng cp trn mt dch v c nh ngha r

    rng da trn vic s dng cc dch v ca cc tng thp hn. V mt lgic, cc tng

    trn gn vi ngi dng hn v lm vic vi d liu tru tng hn, chng da vocc giao thc tng cp di bin i d liu thnh cc dng m cui cng c th

    c truyn i mt cch vt l.

    - M hnh OSI miu t mt tp c nh gm 7 tng m mt s nh sn xut la

    chn v n c th c so snh tng i vi b giao thc TCP/IP. S so snh ny c

    th gy nhm ln hoc mang li s hiu bit su hn v b giao thc TCP/IP.

    1.3. Giao thc UDP:- UDP (User Datagram Protocol) l mt trong nhng giao thc ct li ca giao

    thc TCP/IP. Dng UDP, chng trnh trn mng my tnh c th gi nhng d liu

    ngn c gi l datagram ti my khc. UDP khng cung cp s tin cy v th t

    truyn nhn m TCP lm; cc gi d liu c th n khng ng th t hoc b mt m

    khng c thng bo. Tuy nhin UDP nhanh v hiu qu hn i vi cc mc tiu nh

    kch thc nh v yu cu kht khe v thi gian. Do bn cht khng trng thi ca n

    nn n hu dng i vi vic tr li cc truy vn nh vi s lng ln ngi yu cu.

    - Nhng ng dng ph bin s dng UDP nh DNS (Domain Name System), ng

    dng streaming media,Voice over IP, Trivial File Transfer Protocol (TFTP), v game

    trc tuyn.

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 6

    http://vi.wikipedia.org/wiki/Ti%E1%BA%BFng_Anhhttp://vi.wikipedia.org/wiki/Giao_th%E1%BB%A9c_truy%E1%BB%81n_th%C3%B4nghttp://vi.wikipedia.org/wiki/Ch%E1%BB%93ng_giao_th%E1%BB%A9chttp://vi.wikipedia.org/wiki/Internethttp://vi.wikipedia.org/wiki/TCPhttp://vi.wikipedia.org/wiki/IPhttp://vi.wikipedia.org/w/index.php?title=Giao_th%E1%BB%A9c_t%E1%BA%A7ng_c%E1%BA%A5p_tr%C3%AAn&action=edit&redlink=1http://vi.wikipedia.org/w/index.php?title=Giao_th%E1%BB%A9c_t%E1%BA%A7ng_c%E1%BA%A5p_d%C6%B0%E1%BB%9Bi&action=edit&redlink=1http://vi.wikipedia.org/wiki/M%C3%B4_h%C3%ACnh_OSIhttp://vi.wikipedia.org/wiki/Giao_th%E1%BB%A9c_TCP/IPhttp://vi.wikipedia.org/wiki/Giao_th%E1%BB%A9c_TCP/IPhttp://vi.wikipedia.org/wiki/M%E1%BA%A1ng_m%C3%A1y_t%C3%ADnhhttp://vi.wikipedia.org/w/index.php?title=Datagram&action=edit&redlink=1http://vi.wikipedia.org/wiki/TCPhttp://vi.wikipedia.org/wiki/DNShttp://vi.wikipedia.org/w/index.php?title=Streaming_media&action=edit&redlink=1http://vi.wikipedia.org/wiki/Voice_over_IPhttp://vi.wikipedia.org/w/index.php?title=Trivial_File_Transfer_Protocol&action=edit&redlink=1http://vi.wikipedia.org/w/index.php?title=Game_tr%E1%BB%B1c_tuy%E1%BA%BFn&action=edit&redlink=1http://vi.wikipedia.org/w/index.php?title=Game_tr%E1%BB%B1c_tuy%E1%BA%BFn&action=edit&redlink=1http://vi.wikipedia.org/wiki/Ti%E1%BA%BFng_Anhhttp://vi.wikipedia.org/wiki/Giao_th%E1%BB%A9c_truy%E1%BB%81n_th%C3%B4nghttp://vi.wikipedia.org/wiki/Ch%E1%BB%93ng_giao_th%E1%BB%A9chttp://vi.wikipedia.org/wiki/Internethttp://vi.wikipedia.org/wiki/TCPhttp://vi.wikipedia.org/wiki/IPhttp://vi.wikipedia.org/w/index.php?title=Giao_th%E1%BB%A9c_t%E1%BA%A7ng_c%E1%BA%A5p_tr%C3%AAn&action=edit&redlink=1http://vi.wikipedia.org/w/index.php?title=Giao_th%E1%BB%A9c_t%E1%BA%A7ng_c%E1%BA%A5p_d%C6%B0%E1%BB%9Bi&action=edit&redlink=1http://vi.wikipedia.org/wiki/M%C3%B4_h%C3%ACnh_OSIhttp://vi.wikipedia.org/wiki/Giao_th%E1%BB%A9c_TCP/IPhttp://vi.wikipedia.org/wiki/Giao_th%E1%BB%A9c_TCP/IPhttp://vi.wikipedia.org/wiki/M%E1%BA%A1ng_m%C3%A1y_t%C3%ADnhhttp://vi.wikipedia.org/w/index.php?title=Datagram&action=edit&redlink=1http://vi.wikipedia.org/wiki/TCPhttp://vi.wikipedia.org/wiki/DNShttp://vi.wikipedia.org/w/index.php?title=Streaming_media&action=edit&redlink=1http://vi.wikipedia.org/wiki/Voice_over_IPhttp://vi.wikipedia.org/w/index.php?title=Trivial_File_Transfer_Protocol&action=edit&redlink=1http://vi.wikipedia.org/w/index.php?title=Game_tr%E1%BB%B1c_tuy%E1%BA%BFn&action=edit&redlink=1http://vi.wikipedia.org/w/index.php?title=Game_tr%E1%BB%B1c_tuy%E1%BA%BFn&action=edit&redlink=1
  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    5/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    Chng 2. THIT K V XY DNG CHNGTRNH

    2.1. LAB1

    2.1.1. Net1

    bi: Vit chng trnh x l chui nhp, dng n khi to i tng URL vtr v thuc tnh ca n

    Chc nng chng trnh:

    - Truy cp vo URL, sau in cc thng tin ca ti nguyn nh:

    o Tn file

    o Tn host

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 7

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    6/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    o S hiu cng

    o Kiu giao thc (https hoc http hoc ftp)

    C ch:

    - Client gi yu cu n SERVER- SERVER tr v thng tin ti nguyn

    - Client xut ra console

    Cc lp v chc nng cc lp:

    - Chng trnh n gin nn ch c hm main m ko c cc thuc tnh hayphng thc

    - Khi bin dch chy ngi s dng truyn i s vo, lc chng trnh shin th cc thng tin

    - S dng lp URL c sn truy cpTrin khai:

    Net1.java

    package Lab1;

    import java.net.*;

    public class Net1 {

    public static void main(String args[]){

    try{URL u=new URL("http://www.vnexpress.net:8080");

    System.out.println("Name of the file is:"+ u.getFile());

    System.out.println("Host name is:"+ u.getHost());

    System.out.println("Port number is:"+ u.getPort());

    System.out.println("Protocol type is:"+ u.getProtocol());

    }catch(MalformedURLException e){

    System.out.println(e);}

    }

    }

    Kt qu:

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 8

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    7/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    2.1.2. Student Manager

    bi: To ra 2 ng dng c lp. ng dng u tin nhn cu lnh cho bngstudents c thuc tnh: name, id v age thm vo bng. Cn ng dng th hai th inra mn hnh thng tin t bng students trn

    Add Student

    Chc nng chng trnh:

    - Kt ni c s d liu

    - Thm mt trng vo c s d liu

    C ch:

    - To kt ni n Driver ca h qun tr c s d liu

    - T , thc thi cu lnh x l CSDL

    - Kim tra vic thm c thnh cng hay ko, nu ko th bo li

    Cc lp v chc nng cc lp:

    - Cng nh lp Net1, lp ny cha hm main, ko c thuc tnh v phngthc g khc

    - To i tng Connection kt ni n Driver ca h qun tr CSDL, nu vicload driver khng thnh cng th thot chng trnh

    - To i tng Statement thc thi cu lnh x l CSDL ( y l Insert), sdng phng thc execute thc thi cc lnh khng cn truy vn, i str v l kiu int, tr v 1 nu thnh cng, v gi tr khc th tht bi

    Get Students1

    Chc nng chng trnh:

    - Kt ni CSDL

    - Truy vn

    C ch:

    - To kt ni n Driver ca h qun tr c s d liu

    - T , thc thi cu lnh truy vn CSDL

    - Xut kt qu ra mn hnh

    1

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 9

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    8/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    Cc lp v chc nng cc lp:

    - Tng t nh lp add student, khi to Statement th s dng phng thcexcecuteQuery thay v execute, kiu tr v l ResultSet

    - T ResultSet tr v, hin th n ln mn hnh

    Trin khai:

    AddStudent.java

    package Lab1;

    import java.sql.*;

    public class AddStudent {

    public static void main(String args[]){

    Connection connection=null;

    try{

    Class.forName("org.gjt.mm.mysql.Driver").newInstance();

    }catch(Exception e){

    System.out.println("Registering the Driver was failed");

    }

    try{

    connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/u

    niversitydb");}catch(Exception e){

    System.out.println("Connection with the DataBase failed");

    e.printStackTrace();

    System.exit(1);

    }

    Statement statement=null;

    try{statement=connection.createStatement();

    boolean temp=statement.execute("insert into students value('AnhTuan,'012','06t3'");

    //boolean temp=statement.execute("insert into students value('"+ args[0] +"','" + args[1]+ "','" + args[2]+ "')");

    if(temp)System.out.println("a line was added to the table");

    }catch(SQLException e){

    e.printStackTrace();

    }finally{

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 10

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    9/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    try{

    statement.close();

    connection.close();

    }catch(SQLException e){

    e.printStackTrace();

    }

    }

    }

    }

    GetStudent.java

    package Lab1;

    import java.sql.*;

    public class GetStudent {

    public static void main(String args[]){

    Connection connection=null;

    try{

    Class.forName("org.gjt.mm.mysql.Driver").newInstance();

    }catch(Exception e){

    System.out.println("Registering the Driver was failed");

    }

    try{

    connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/universityDB");

    }catch(Exception e){

    System.out.println("Connection with the DataBase failed");

    e.printStackTrace();

    System.exit(1);

    }

    Statement statement=null;

    try{

    statement=connection.createStatement();

    ResultSet result=statement.executeQuery("select * from student");

    while(result.next()){

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 11

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    10/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    System.out.println(result.getString(1)+ "," + result.getString(2) + "," +result.getString(3));

    }

    }catch(SQLException e){

    e.printStackTrace();

    }finally{

    try{

    statement.close();

    connection.close();

    }catch(SQLException e){

    e.printStackTrace();

    }

    }

    }

    }

    Kt qu:

    2.1.3. NumberTCPSimple

    bi: To ra hai ng dng c lp (mt client v mt server). Client chp nhnmt trong cc s sau: 1, 2, 3. S ny s c gi n server. Server s tr li tng

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 12

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    11/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    ng : ONE hoc TWO hoc THREE (ty theo s nhn c). Dng giao thcTCP/IP

    Chc nng chng trnh:

    - Client gi s bt k n SERVER

    - Nu l s 1,2,3 th tr v ONE,TWO,THREE, cc trng hp cn li tr vUNKNOWN

    C ch:

    - SERVER m cng client truy xut n

    - To cc lung nhp xut khi c client truy cp n (c client v SERVER),lc ny client v server c th gi thng tin qua li ln nhau

    - Client truy cp vo, sau gi thng tin n server

    - Server nhn c thng tin, ri x l, sau gi tr li client- Client hin th thng tin m server tr v

    Cc lp v chc nng cc lp:

    NumberTCPSimpleServer

    - Lp ny c phng thc go(), chc nng ca n:

    o M cng ca server, to kt ni mi khi c client kt ni

    o Ch nhn d liu t Client gi ln

    o X l d liuo Tr v client

    - Phng thc main ca lp ny to ra i tng thuc lpNumberTCPSimpleServer, sau gi phng thc go() ca lp ny

    NumberTCPSimpleClient

    - Phng thc khi to ca lp ny c i s l chui v a ch ca server

    - Phng thc go():

    o To kt ni n a ch v s hiu cng ca server

    o To cc lung nhp xut lin kt vi server

    o a d liu cn gi hoc nhn vo cc lung ny

    o Gi d liu n server

    o Nhn d liu (sau khi server x l) ri hin th ln mn hnh

    Trin khai:

    NumbersTCPSimpleClient.java

    package Lab1.Cau3;import java.io.*;

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 13

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    12/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    import java.net.*;

    public class NumbersTCPSimpleClient {

    public static final int DT_PORT=1300;

    String hostName;

    Socket soc;

    public static void main(String args[]){

    NumbersTCPSimpleClient client=new NumbersTCPSimpleClient("localhost");

    try{

    client.go("1");

    }catch(IOException e){

    e.printStackTrace();

    }catch(ClassNotFoundException e){

    e.printStackTrace();

    }

    }

    public NumbersTCPSimpleClient(String hostString){

    this.hostName=hostString;

    }

    public void go(String str)throws IOException,ClassNotFoundException{

    soc=new Socket(hostName,DT_PORT);

    //creating an InputStream that will be connect to soc

    InputStream is=soc.getInputStream();

    //creating an ObjectInputStream object

    ObjectInputStream ois=new ObjectInputStream(is);

    //creating an OutputStream that will be connect to soc

    OutputStream os=soc.getOutputStream();

    //creating an ObjectOutputStream object

    ObjectOutputStream oos=new ObjectOutputStream(os);

    //sending data to server

    oos.writeObject(str);

    System.out.println(str+" was sent");

    //receive from server

    String temp=(String)ois.readObject();

    System.out.println(temp+" was receive");

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 14

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    13/34

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    14/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    //creating an ObjectOutputStream object

    ObjectOutputStream oos=new ObjectOutputStream(os);

    //creating an InputStream object

    InputStream is=soc.getInputStream();

    //creating an ObjectInputStream object

    ObjectInputStream ois=new ObjectInputStream(is);

    String receive=(String)ois.readObject();

    String returned=null;

    if(receive.equals("1"))

    returned="ONE";

    else

    if(receive.equals("2"))

    returned="TWO";

    else

    if(receive.equals("3"))

    returned="THREE";

    else

    returned="UNKNOWN";

    oos.writeObject(returned);

    oos.close();

    ois.close();

    soc.close();

    }

    }

    }

    Kt qu:

    Client

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 16

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    15/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    SERVER

    2.2. LAB2

    2.2.1. Net1

    bi: Vit chng trnh lit k ton b ni dung ca bt k trang web no trn net

    Chc nng chng trnh:

    - Hin th thng tin ton b trang web ca bt k trang web no di dng textn thun

    C ch:

    - Gi a ch URL

    - Web server tr li thng tin

    - Truy xut n thng tin cn thit v hin thCc lp v chc nng cc lp:

    - Ch gm mt phng thc main:

    o Lin kt n URL vi a ch c nhp vo

    o S dng phng thc getContent() ca i tng URL nhn tonb ni dung ca trang web

    o c ton b ni dung v hin th ln mn hnh

    Trin khai:

    net1.java

    package Lab2;

    import java.net.*;

    import java.io.*;

    public class net1 {

    public static void main(String args[]){

    int i;

    BufferedInputStream bis;

    try{

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 17

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    16/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    URL u=new URL("http://www.thanhnien.com.vn");

    bis=new BufferedInputStream((InputStream)u.getContent());

    while((i=bis.read())>0){

    System.out.print((char)i);

    //System.out.println();

    }

    }catch(MalformedURLException e){

    System.out.println(e);

    }

    catch(IOException e){

    System.out.println(e);

    }

    }

    }

    Kt qu:

    2.2.2. Net2

    bi: Vit chng trnh gi n URL mt chui, m kt ni t URL ny v hinth thng tin header

    Chc nng chng trnh:

    - M kt ni n a ch URL

    - Hin th thng tin cc header nhn c

    C ch:

    - Truy xut n a ch URL

    - To kt ni n n

    - Ly thng tin v Header

    - Hin th ln mn hnh

    Cc lp v chc nng cc lp:

    - Cng ch c phng thc main:

    o To URL kt ni n a ch nhp vo

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 18

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    17/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    o M kt ni (s dng phng thc openConnection ca i tngURL)

    o Ly thng tin header (dng phng thc getHeaderField,getHeaderFieldKey ca i tng URLconnection)

    o Hin th thng tin header

    o In thng bo li nu c li xy ra

    Trin khai:

    net2.java

    package Lab2;

    import java.net.*;

    import java.io.*;

    public class net2 {

    public static void main(String args[]){

    int i=1;

    BufferedInputStream bis;

    try{

    URL ul=new URL("http://www.thanhnien.com.vn");

    URLConnection u=ul.openConnection();

    String s=u.getHeaderField(i);

    String sg=u.getHeaderFieldKey(i);

    while(s!=null){

    System.out.println("Header "+i+": "+sg+" = "+s);

    i++;

    s=u.getHeaderField(i);

    sg=u.getHeaderFieldKey(i);

    }}catch(MalformedURLException e){

    System.out.println(e);

    }

    catch(IOException e){

    System.out.println(e);

    }

    }}

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 19

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    18/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    Kt qu:

    2.2.3. Net3

    bi: Vit chng trnh in ra a ch ca localhost (a ch cc b), null host va ch bt k trn internet

    Chc nng chng trnh:

    - Hin th thng tin v a ch cc b, a ch null v a ch bt k trn internet

    C ch:

    Cc lp v chc nng cc lp:

    - To i tng InetAddress

    - S dng phng thc getLocalHost() ly thng tin v a ch cc b vhin th n

    - S dng phng thc getByName(null) ly thng tin v a ch null vhin th n

    - S dng phng thc getByName(URL) ly thng tin v a ch URL camt website v hin th n

    - Hin th li nu c

    Trin khai:

    Net3.javapackage Lab2;

    import java.io.*;

    import java.net.*;

    public class net3 {

    public static void main(String args[]){

    InetAddress i;

    try{

    i=InetAddress.getLocalHost();

    System.out.println("The localhost is: "+ i);

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 20

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    19/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    i=InetAddress.getByName(null);

    System.out.println("The Null host is: "+ i);

    i=InetAddress.getByName("www.yahoo.com");

    System.out.println("Yahoo Host address is: "+i);

    }catch(IOException e){

    System.out.println(e);

    }

    }

    }

    Kt qu:

    2.2.4. Net4

    bi: Vit chng trnh m kt ni dng i tng URL v kim tra cc thuctnh v ni dung ca ti nguyn nhn c.

    Chc nng chng trnh:

    - Hin th cc thng tin v ti nguyn nhn c trn internet nh ngy to,ngy chnh sa sau cng, ngy ht hn

    C ch:

    Cc lp v chc nng cc lp:

    - Tng t nh Net3, thay v s dng phng thc getHeaderField th s dnggetDate(), getContentType() ca i tng URLConnection thay th

    - Duyt ht ton b ni dung v hin th ra mn hnh

    Trin khai:

    net4.java

    package Lab2;

    import java.net.*;

    import java.io.*;import java.util.*;

    public class net4 {

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 21

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    20/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    public static void main(String args[])throws IOException{

    int i;

    URL ul=new URL("http://www.24.com.vn");

    URLConnection u=ul.openConnection();

    System.out.println("Date: "+ new Date(u.getDate()));

    System.out.println("Content-type:"+u.getContentType());

    System.out.println("Expires: "+u.getExpiration());

    System.out.println("Last Modified: "+u.getLastModified());

    int l=u.getContentLength();

    System.out.println("Content_length: "+ l);

    if(l>0){

    System.out.println("Content");

    InputStream is=u.getInputStream();

    int a=l;

    while(((i=is.read())!=-1)&&(--a>0)){

    System.out.print((char)i);

    }

    is.close();

    }

    else

    System.out.println("Content is not available");

    }

    }

    Kt qu:

    2.2.5. KnockKnock bi:Vit ng dng minh ha gi d liu n server v client x l n

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 22

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    21/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    V d hai chng trnh c lp chy trn JAVA: chng trnh client v chng trnhserver. Chng trnh client thc thi mt lp KnockKnockClient. Chng trnh serverthc thi hai lp: KnockKnockServer v KnockKnockProtocol. KnockKnockServercha phng thc main cho chng trnh server v m cng, kt ni v c, gi d liun socket, cn KnockKnockProtocol x l jokes. N theo di cc joke hin ti, trng

    thi hin ti (gi knock knock, gi clue, v.v). v tr v gi tr khc nhau ca joke catrng thi hin ti. i tng thc thi giao thc xc inh ngn ng giao tip giaclient v server

    Chc nng chng trnh:

    - Mt chng trnh vui nhn, trao i thng ip client-server qua li ln nhau,ta nh chat hoc game

    C ch:

    - Dng c ch client/server gi nhn thng ip

    Cc lp v chc nng cc lp:

    - Khi client v server kt ni vi nhau th Server s hin th Knock!Knock!

    - Nu ngi s dng gi Whos there?, server s gi tn hin ti ca ngi trong chui clues vi ch s l currentJoke l ch s ca ngi hin ti

    - Nu tip tc gi tn ca ngi hin ti + who? (Tc l hi h l ai), th nkt hp vi chui answers tr li cho client

    - Server s hi c mun tip tc khng, nu client ng th n s chuyn nngi tip theo l ngi hin hnh, c nh vy cho n khi ngi s dng

    khng mun tip tc naTrin khai:

    KnockKnockServer.java

    package Lab2.Cau5;

    import java.io.*;

    import java.net.*;

    public class KnockKnockServer {

    public static void main(String args[])throws IOException{ServerSocket serverSocket=null;

    try{

    serverSocket=new ServerSocket(4444);

    }catch(IOException e){

    System.err.println("Could not listen on port: 4444");

    System.exit(1);

    }Socket clientSocket=null;

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 23

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    22/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    try{

    clientSocket=serverSocket.accept();

    }catch(IOException e){

    System.err.println("Accept failed");

    System.exit(1);

    }

    PrintWriter out=new PrintWriter(clientSocket.getOutputStream(),true);

    BufferedReader in=new BufferedReader(newInputStreamReader(clientSocket.getInputStream()));

    String inputLine,outputLine;

    KnockKnockProtocol kkp=new KnockKnockProtocol();

    outputLine=kkp.processInput(null);

    out.println(outputLine);

    while((inputLine=in.readLine())!=null){

    outputLine=kkp.processInput(inputLine);

    out.println(outputLine);

    if(outputLine.equals("Bye!"))break;

    }

    out.close();

    in.close();

    clientSocket.close();

    serverSocket.close();

    }

    }

    KnockKnockProtocol.java

    package Lab2.Cau5;

    public class KnockKnockProtocol {

    private static final int WAITING=0;

    private static final int SENTKNOCKKNOCK=1;

    private static final int SENTCLUE=2;

    private static final int ANOTHER=3;

    private static final int NUMJOKES=5;

    private int state=WAITING;private int currentJoke=0;

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 24

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    23/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    private String []clues={"Turnip","Little Old Lady","Atch","Who","Who"};

    private String []answers={"Turnip the heat, it's cold in here!","I didn't know youcould yodel!","Bless you!","Is there an owl in here?","Is there an echo in here?"};

    public String processInput(String theInput){

    String theOutput=null;

    if(state==WAITING){

    theOutput="Knock! Knock!";

    state =SENTKNOCKKNOCK;

    }

    else if(state==SENTKNOCKKNOCK){

    if(theInput.equalsIgnoreCase("Who's there?")){

    theOutput=clues[currentJoke];

    state=SENTCLUE;

    }else theOutput="You're supposed to say \"Who there?\"!"+"Try again.Knock! Knock!";

    }

    else if (state == SENTCLUE) {

    if(theInput.equalsIgnoreCase(clues[currentJoke])){

    theOutput=answers[currentJoke]+ "Want another? (y/n)";state=ANOTHER;

    }else{

    theOutput="You're supposed to say \""+clues[currentJoke]+ " Who?\""+"!Try again. Knock! Knock!";

    state=SENTKNOCKKNOCK;

    }

    }

    else if(state==ANOTHER){

    if(theInput.equalsIgnoreCase("y")){

    theOutput="Knock! Knock!";

    if(currentJoke==NUMJOKES-1)

    currentJoke=0;

    else

    currentJoke++;

    state=SENTKNOCKKNOCK;

    }else{

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 25

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    24/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    theOutput="Bye!";

    state=WAITING;

    }

    }

    return theOutput;

    }

    }

    KnockKnockClient.java

    package Lab2.Cau5;

    import java.net.*;

    import java.io.*;

    public class KnockKnockClient {

    public static void main(String args[])throws IOException{

    Socket kkSocket=null;

    PrintWriter out=null;

    BufferedReader in=null;

    try{

    kkSocket=new Socket("localhost",4444);

    out=new PrintWriter(kkSocket.getOutputStream(),true);

    in=new BufferedReader(newInputStreamReader(kkSocket.getInputStream()));

    }catch(UnknownHostException e){

    System.err.println("Don't known about host: localhost");

    System.exit(1);

    }catch(IOException e){

    System.err.println("Couldn't get I/O for the connection to: localhost");

    System.exit(1);

    }

    BufferedReader stdIn=new BufferedReader(newInputStreamReader(System.in));

    String fromServer;

    String fromUser;

    while((fromServer=in.readLine())!=null){System.out.println("Server: "+ fromServer);

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 26

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    25/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    if(fromServer.equals("Bye!"))break;

    fromUser=stdIn.readLine();

    if(fromUser!=null){

    System.out.println("Client: "+ fromUser);

    out.print(fromUser);

    }

    }

    out.close();

    in.close();

    stdIn.close();

    kkSocket.close();

    }

    }

    Kt qu:

    SERVER

    CLIENT

    2.3. LAB3

    2.3.1. MulticastPeer

    bi: Xy dng chng trnh multicast theo mu bn di

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 27

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    26/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    Chc nng chng trnh:

    - Tham gia vo group ca multicast

    - Gi d liu n a ch multicast

    - Nhn d liu t multicast

    - Hin th ln mn hnh

    - Ch cn cc client tham gia vo group ca a ch multicast ny th khi c dliu c gi vo th tt c client u nhn c

    C ch:

    - Tham gia vo group ca a ch multicast

    - Gi d liu n a ch multicast (Lc ny cc client mun nhn c thphi tham gia vo group ca multicast th mi nhn c)

    - V trong chng trnh cng tham gia vo group multicast nn n cng snhn c d liu khi c client gi vo a ch ny

    Cc lp v chc nng cc lp:

    - Chy chng trnh gm 2 i s: i s u tin v d liu cn gi i, i sth 2 l a ch multicast

    - Ch gm mt phng thc main():

    - To cng lin kt n multicast

    - Tham gia vo group multicast

    - Chuyn i s th nht thnh mng byte, ri to i tng DatagramPacket gi d liu i (gi phng thc send ca i tng DatagramPacket)

    - Gi phng thc receive nhn d liu t a ch multicast

    - Ri khi nhm multicast khng nhn d liu t a ch ny na

    Trin khai:

    MulticasPeer.java

    package Lab3;

    import java.net.*;import java.io.*;

    public class MulticasPeer {

    public static void main(String args[]){

    MulticastSocket s=null;

    try{

    InetAddress group=InetAddress.getByName(args[1]);

    //The hard-coded port number in 6789(the client must have aMulticastSocket bound to this port)

    s=new MulticastSocket(6789);

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 28

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    27/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    //The input InetAddress is the multicase group

    s.joinGroup(group);

    byte []m=args[0].getBytes();

    DatagramPacket dp= new DatagramPacket(m,m.length,group,6789);

    s.send(dp);

    //buffer used to receive

    byte []buffer=new byte[1000];

    for(int i=0;i

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    28/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    - Cc client hin th cc thng tin nhn c t server

    C ch:

    - Server c tng dng d liu t file one-liners.txt

    - Vi mi dng d liu, gi n n a ch multicast l 230.0.0.1, mi ln giserver tm dng vi giy (l bi s ca 5)

    - Tt c cc client tham gia vo multicast trn s nhn c d liu t servergi n (bnh thng nu theo c ch TCP s lm kh hn)

    - Client hin th n ln mn hnh ca mnh, trong chng trnh c thit kch nhn 5 dng

    Cc lp v chc nng cc lp:

    Lp QuoteServerThread:

    - C 2 phng thc khi to, khng c i s hoc c 1 i s l tn- Trong phng thc khi to, m cng 4445, thc t cng s bao nhiu

    khng quan trng trong trng hp ny, v n ch gi n a ch multicast,c d liu t file one-liners.txt

    - Phng thc getNextQuote() c tng dng d liu trong file, tr v gitr chui tm c hoc No more quote. Good bye! nu khng tm thy

    Lp MultiserverThread:

    - K tha t lp QuoteServerThread

    - c tng dng d liu- Vi mi dng d liu th x l:

    o Gi dng d liu n a ch multicast

    o Tm dng mt thi gian (bi s ca 5) giy

    Lp MulticastServer:

    - To i tng MultiserverThread v start n

    Lp MulticastClient:

    - Tham gia vo group multicast ca a ch 230.0.0.1- Nhn d liu t server gi n

    - Hin th n trn mn hnh

    - Chng trnh client c thit k nhn 5 dng d liu

    Trin khai:

    MulticastServer.java

    package Lab3.Cau2;

    public class MulticastServer {public static void main(String args[]){

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 30

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    29/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    try{

    new MulticastServerThread().start();

    }catch(java.io.IOException e){

    }

    }

    }

    MulticastServerThread.java

    package Lab3.Cau2;

    import java.io.*;

    import java.net.*;

    import java.util.*;

    public class MulticastServerThread extends QuoteServerThread{

    private long FIVE_SECONTS=5000;

    public MulticastServerThread() throws IOException{

    super("MulticastServerThread");

    }

    public void run(){

    while(moreQoutes){

    try{

    byte []buf=new byte[256];

    //contruct quote

    String dString=null;

    if(in==null)

    dString=new Date().toString();

    else

    dString=getNextQoute();

    buf=dString.getBytes();

    InetAddress group=InetAddress.getByName("230.0.0.1");

    DatagramPacket packet=new DatagramPacket(buf,buf.length,group,4446);

    socket.send(packet);

    //sleep for a while

    try{sleep((long)(Math.random()*FIVE_SECONTS));

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 31

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    30/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    }catch(InterruptedException e){}

    }catch(IOException e){

    e.printStackTrace();

    moreQoutes=false;

    }

    }

    socket.close();

    }

    }

    QuoteServerThread.java

    package Lab3.Cau2;

    import java.io.*;

    import java.net.*;

    public class QuoteServerThread extends Thread{

    protected DatagramSocket socket=null;

    protected BufferedReader in=null;

    protected boolean moreQoutes=true;

    private static int TTL=128;

    public QuoteServerThread()throws IOException{

    this("QouteServerThread");

    }

    public QuoteServerThread(String name)throws IOException{

    super(name);

    socket=new DatagramSocket(4445);

    try{

    in=new BufferedReader(new FileReader("one-liners.txt"));

    }catch(FileNotFoundException e){

    System.out.println("Could not open qoute file. Serving time instead");

    }

    }

    protected String getNextQoute(){

    String returnValue=null;

    try{

    if((returnValue=in.readLine())==null){

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 32

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    31/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    in.close();

    moreQoutes=false;

    returnValue="No more qoutes. Goodbye.";

    }

    }catch(IOException e){

    returnValue="IOException occurred in server.";

    }

    return returnValue;

    }

    }

    MulticastClient.java

    package Lab3.Cau2;

    import java.io.*;

    import java.net.*;

    import java.util.*;

    public class MulticastClient {

    public static void main(String args[])throws IOException{

    MulticastSocket socket=new MulticastSocket(4445);

    InetAddress address=InetAddress.getByName("203.0.0.1");

    socket.joinGroup(address);

    DatagramPacket packet;

    //get a few qoute

    for(int i=0;i

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    32/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    Client

    Server ch x l chui khng hin th nn khng a vo

    Chng 3. KT LUN V HNG PHT TRIN

    1. Nhng kt qu t c

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 34

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    33/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    - Hiu r hn v TCP, UDP

    - C th to mt chng trnh TCP, UDP n gin

    - Kt qu ca chng trnh c th hin phn phn tch ca mi chngtrnh

    2. Nhng vn tn ti

    - Chng trnh c vit th cc tnh nng, nhiu lp cha thit k tt (lp

    ch c mi hm main)

    - Cha trin khai trn nhiu my tnh khc nhau

    - Cha c giao din ha

    3. Hng pht trin

    - Thit k giao din ha

    - Cc chng trnh TCP thit k multithread

    - To cc phng thc cho mi chc nng, khng nn a ht v hm main

    SVTH: Trn Anh Tun _06T3 _Nhm 8A 35

  • 8/6/2019 Tran Anh Tuan_06T3_102103061149

    34/34

    Thc hnh lp trnh mng GVHD: Nguyn Vn Nguyn

    LI CM N

    - Hc phn thc hnh lp trnh mng gip chng em bit thm kin thc cn

    bn v lp trnh. Kt hp nhiu my tnh li vi nhau to thnh mt h thng ln hn.

    T kin thc cn bn lm nn tng c th tip thu thm kin thc, nng cao nng

    lc bn thn.

    - Em xin gi li cm n n thy Nguyn Vn Nguyn v cc thy c tn tnh

    gip , hng dn lp trnh trong nhng lc kh khn.


Recommended