Top Banner
38

Presents the network programming in Java language. 1 ... · PDF file05.01.2013 · Presents the network programming in Java language. ... Internet address ... diễn một liên.....

Feb 06, 2018

Download

Documents

lyxuyen
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • Presents the network programming in Java language.

    Main points:

    1) Discuss the usage of java.net package.

    2) Introduce the Java implementation for UDP protocol.

    3) Introduce the New I/O API.

  • Why use Java for Networking?a) Java was the first programming language designed

    from the ground up with networking in mind.b) Java provides easy solutions to two crucial problem b) Java provides easy solutions to two crucial problem

    for Internet networking platform independence and security.

    c) It is far easier to write network programs in Java than in almost any other language.

    d) In the fully functional applications, very little code is devoted to networking.

  • Internet address ( IP address) is a unique number for identifying a device connected to the Internet.

    The current standard is IPv4 which are four bytes long.

    The hostname and IP address is, in Java, represented by java.net.InetAddress.

    InetAddress is used by many other networking classes, including Socket, ServerSocket, URL, DatagramSocket, DatagramPacket, and more.

  • No public constructor Three static methods:

    o InetAddress getByName(String hostname) Static method used to retrieve the address for the host name

    passed as the parameter.InetAddress [ ] getAllByName(String hostname)o InetAddress [ ] getAllByName(String hostname) Static method used to retrieve all the addresses for the host name

    passed as a parameter.o InetAddress getLocalHost( )

    Static method used to retrieve the address for the current, or local, host.

    Tt c cc phng thc ny u thc hin kt ni ti server DNS cc b bit c cc thng tin trong i tng InetAddress

  • try{

    InetAddress dc =InetAddress.getByName(www.microsoft.com);

    System.out.println(dc);

    }}

    catch(UnknownHostException e)

    {

    System.err.println(e);

    }

  • import java.net.*;

    public class TimDCIP {

    public static void main(String[] args) {

    try {

    if(args.length!=1) {

    System.out.println("Cach su dung: java TimDCIP ");

    }}

    InetAddress host = InetAddress.getByName(args[0]);

    String hostName = host.getHostName();

    System.out.println("Host name:"+hostName);

    System.out.println("Dia chi IP:"+host.getHostAddress());

    } catch(UnknownHostException e) {

    System.out.println("Khong tim thay dia chi");

    return;

    }

    }

    }

  • Useful methodso String getHostName( )

    Returns the host name.

    o byte[ ] getAddress( ) o byte[ ] getAddress( )

    Returns the IP address.

    o String getHostAddress( )

    Returns the IP address as a string.

  • import java.net.*;public class IISTByName{

    public static void main(String [ ] args){try {try {

    InetAddress address = InetAddress.getByName(www.iist.unu.edu);

    System.out.println(address);} catch (UnkownHostException ex){

    System.out.println(Could not find www.iist.unu.edu);}

    }}

  • import java.net.*;public class PhanLoaiDCIP{

    public static void main(String[] args) {

    try{if(args.length!=1){

    System.out.println("Cach su dung: java TimDCIP ");

    }InetAddress host = InetAddress.getByName(args[0]);String hostName = host.getHostName();System.out.println("Host name:"+hostName);

  • System.out.println("Dia chi IP:"+host.getHostAddress());

    byte[] b=host.getAddress();

    int i=b[0]>=0?b[0]:256+b[0];

    if((i>=1)&(i

  • The java.net.URL is an abstraction of a Uniform Resource Locator (URL).

    URLs are composed of five pieces:1. The scheme, also known as the protocol1. The scheme, also known as the protocol2. The authority3. The path4. The query string5. The fragment identifier, also known as the section or ref://?#

  • For example, given the URL :

    http://www.ibiblio.org/javafaq/javabooks/index.html?isbn=123456789#toc=123456789#toc

    1. scheme : http

    2. authority : www.ibiblio.org

    3. path : /javafaq/books/javabooks/index.html

    4. query string : isbn=123456789

    5. fragment identifier : toc

  • The authority may further be divided into the user info, the host,and the port.

    For example, in the URL http://[email protected]:8080/http://[email protected]:8080/

    1. user info : admin

    2. host : www.blackstar.com

    3. port : 8080

  • The java.net.URL class provides static methods for getting the abovementioned information:

    a) public String getFile( ) // path + queryPhng thc getFile() tr v mt xu k t cha phn ng dn ca mt URL; Java khng phn chia mt URL thnh cc phn ng dn v phn tp tin ring bit. phn tp tin ring bit.

    b) public String getHost() Phng thc getHost() tr v mt xu k t biu din phn hostname ca URL.

    c) public int getPort( )Phng thc getPort() tr v mt s nguyn kiu int biu din s hiu cng c trong URL.

    d) public String getProtocol()Phng thc getProtocol() tr v mt xu k t biu din phn giao thc ca URL

  • e) public String getRef()Phng thc ny tr v phn nh danh on ca URLf) getQuery( )g) getPath( )h) getUserInfo( )h) getUserInfo( )i) getAuthority( )

  • URL(String spec) throws MalformedURLException

    o Creates a URL object from the String representation.

    URL(String protocol, String host, int port, String file) throws MalformedURLExceptionthrows MalformedURLException

    o Creates a URL object from the specified protocol, host, port number, and file.

    URL(String protocol, String host, String file) throws MalformedURLExceptiono Creates a URL from the specified protocol name, host name, and

    file name.

  • import java.net.*;public class ProtocolTester{

    public static void testProtocol(String url){try {

    URL u = new URL (url);URL u = new URL (url);System.out.println(u.getProtocol() + is supported);

    } catch (MalformedURLException ex){String protocol = url.substring(0,url.indexOf(:));System.out.println(protocol + is not supported);

    }}

    }

  • You can test it with the following Tester

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

    ProtocolTester.testProtocol (http://www.adc.org);ProtocolTester.testProtocol (http://www.adc.org);

    ProtocolTester.testProtocol (http://www.amazon.com/exec/obidos/order2);

    ProtocolTester.testProtocol (ftp://metalab.unc.edu/pub/languages/java/javafap);

    }}

  • URL u1,u2;

    try{

    URL u1= new URL(http://www.macfaq.com/index.html);

    URL u2 = new URL(u1,vendor.html);

    }}

    catch(MalformedURLException e)

    {

    System.err.println(e);

    }

  • //Chng trnh ly thng tin ca URL vi cc thng tin nhp t bn phm

    import java.net.*;

    class getURLParts{

    public static void main(String[] args) {

    try {

    URL u = new URL(args[0]);URL u = new URL(args[0]);

    System.out.println("URL is "+u);

    System.out.println("The protocol part is "+u.getProtocol());

    System.out.println("The host part is "+u.getHost());

    System.out.println("The file part is "+u.getFile());

    System.out.println("The reference part is "+u.getRef());

    } catch(MalformedURLException e) { System.err.println(e); }

    }

    }

  • Lp java.net.URL c ba phng thc tm kim d liu t mt URL

    public final InputStream openStream() throws java.io.IOException

    Phng thc ny kt ni ti mt ti nguyn c tham chiu bi mt URL, thc hin c ch bt tay cn thit gia client v bi mt URL, thc hin c ch bt tay cn thit gia client v server, v tr v mt lung nhp InputStream. Ta s dng lung ny c d liu. D liu nhn t lung ny l d liu th ca mt tp tin m URL tham chiu (m ASCII nu c mt tp vn bn, m HTML nu c mt ti liu HTML, mt nh nh phn nu ta c mt file nh). N khng c cc thng tin header v cc thng tin c. lin quan n giao thc

  • public URLConnection openConnection() throws java.io.IOException

    Phng thc opeConnection() m mt socket ti mt URL xc nh v tr v mt i tng URL. Mt i tng URLConnection biu din mt lin kt m ti mt ti nguyn mng. Nu li gi phng thc tht bi n a ra ngoi l IOException.

    public final Object getConetent() throws java.io.IOException public final Object getConetent() throws java.io.IOException

    Phng thc ny cung cp cch th ba ti d liu c tham chiu bi mt URL. Phng thc getContent() tm kim d liu c tham chiu bi mt URL v chuyn n thnh mt kiu i tng no . Nu i tng tham chiu ti mt kiu i tng vn bn no nh tp tin ASCII hoc tp HTML, i tng c tr v thng thng s l mt kiu lung nhp InputStream no . Nu URL tham chiu ti mt i tng nh nh nh GIF hoc JPEG th phng thc getContent() tr v i tng java.awt.ImageProducer

  • Procedure to use the methods:

    1) Create an URL object

    e.g. URL u = new URL("http://www.iist.unu.edu");

    2) Open an InputStream object directly from the URL object e.g. InputStream in = u.openStream( );e.g. InputStream in = u.openStream( );

    3) Or open an URLConnection object from the URL object and then get an InputStream object from the URLConnection object .

    e.g.

    URLConnection uc = u.openConnection( );

    InputStream in = uc.getInputStream( );

    4) In either case, you will have an InputStream. Whats followed is the normal I/O procedure for getting data.

    5) Dont forget to put the try catch block for catching the MalformedURLException and IOException.

  • import java.net.*;

    import java.io.*;

    public class ViewSource {

    public static void main(String[] args) {

    URL u;

    String thisLine;

    if(args.length>0) {if(args.length>0) {

    try { u =new URL(args[0]);

    try {

    DataInputStream dis = new DataInputStream(u.openStream());

    while((thisLine=dis.readLine())!=null) System.out.println(thisLine);

    } catch(IOException e) { System.err.println(e); }

    } catch(Ma