Java Networking by Kamalakar Dandu

Embed Size (px)

Citation preview

  • 8/2/2019 Java Networking by Kamalakar Dandu

    1/65

    Introduction Internet Addresses

    Server Sockets and Sockets Datagram Sockets and Packets

    Uniform Resource Locators

    Java Networking

  • 8/2/2019 Java Networking by Kamalakar Dandu

    2/65

    The InetAddress Class

    The java.net.InetAddress classrepresents an IP address.

    It converts numeric addresses tohost names and host names to

    numeric addresses. It is used by other network

    classes like Socket and

    ServerSocket to identify hosts.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    3/65

    Creating InetAddresses

    There are no public

    InetAddress() constructors.Arbitrary addresses may not becreated.

    All addresses that are created

    must be checked with DNS.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    4/65

    getByName() Method

    public static InetAddress getByName(String host)throws UnknownHostException

    InetAddress inetadd;

    try {

    inetadd=InetAddress.getByName("utopia.poly.edu");

    // or you could pass an ip address also

    // inetadd = InetAddress.getByName("128.238.2.92");}

    catch (UnknownHostException e) {

    System.err.println(e);

  • 8/2/2019 Java Networking by Kamalakar Dandu

    5/65

    getByName()

    If parameter name is null, then itsearches for the localhost

    One can also pass localhost as

    a parameter to look for the localhost

    One can also find local host bypassing the ip address

    127.0.0.1 as a parameter

  • 8/2/2019 Java Networking by Kamalakar Dandu

    6/65

    class Namepublic

    methods

    InetAddress Class

    InetAddress implements Serializable

    //no constructors

    String getHostName()

    String getHostAddress()

    byte getAddress()[]boolean isMulticastAddress()

    static InetAddress getByName(String)

    static InetAddress[] getAllByName(String)

    static InetAddress getLocalHost()

    throws UnknownHostException

    Eg:testservernames.java

  • 8/2/2019 Java Networking by Kamalakar Dandu

    7/65

    The java.net.URL class

    A URL object represents a URL.

    The URL class contains methods

    to. create new URLs.

    parse the different parts of a URL.

    get an input stream from a URL soyou can read data from a server.

    get content from the server as a

    Java object.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    8/65

    URL(String u)URL(String protocol, String host, String file)URL(String protocol, String host, int port, String file)

    URL(URL context, String url)URL(String protocol, String host, int port, String file,

    URLStreamHandler handler) /* 1.2 */URL(URL context, String url, URLStreamHandler

    handler) /* 1.2 */

    All the above constructors are public and all of them

    are declared as throws MalformedURLException

    URL Constructors

  • 8/2/2019 Java Networking by Kamalakar Dandu

    9/65

    An example of an absolute URL is

    http://www.mypersonal.com:8080/cs1/st

    art.html#first"

    try {

    }

    catch (MalformedURLException e) { }URL u = new URL("http", "www.mypersonal.com",8080, "/cs1/start.html#first");

    URL u = new

    URL("http://www.mypersonal.com:8080/cs1/start.html#first");

    Constructing URL Objects

  • 8/2/2019 Java Networking by Kamalakar Dandu

    10/65

    Relative URLs

    Many HTML files contain relativeURLs.

    Consider the pagehttp://intranet.satyam.com/home.ht

    ml. On this page a link to library refers

    to library/default.html.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    11/65

    Constructing Relative URLs

    The fourth constructor creates URLsrelative to a given URL. For example,

    try {URL u1 = newURL("http://intranet.satyam.com/home.html");

    URL u2 = new URL(u1, "library/default.html");

    }

    catch (MalformedURLException e) {}

  • 8/2/2019 Java Networking by Kamalakar Dandu

    12/65

    Info From URLs

    The java.net.URL class has fivemethods to split a URL into itscomponent parts. These are:

    public String getProtocol()

    public String getHost()public int getPort()

    public String getFile()

    public String getRef()

  • 8/2/2019 Java Networking by Kamalakar Dandu

    13/65

    Construct a URL by passing the stringhttp://www.mypersonal.com:8080/start.

    html#first as a parameter

    Display the individual parts of the URLlike

    protocol, host, port, file and reference if

    any

    Construct a relative URL and displaythe info for the newly constructed URL

    also

    Eg: urlMethodsDemo.java

    URLs

  • 8/2/2019 Java Networking by Kamalakar Dandu

    14/65

    URL - Observations If a port is not explicitly specified in

    the URL it's set to -1. This meansthe default port is to be used.

    If the ref doesn't exist, it's just null,

    so watch out forNullPointerExceptions. Better yet,test to see that it's non-null beforeusing it.

    If the file is left off completely, e.G.

    Http://java.Sun.Com, then it's set to" "

  • 8/2/2019 Java Networking by Kamalakar Dandu

    15/65

    Reading Data From a URL

    The openStream() method connects to theserver specified in the URL and returns anInputStream object fed by the data from thatconnection.

    public final InputStream openStream() throwsIOException.

    Any headers that precede the actual dataare stripped off before the stream is opened.

    Network connections are less reliable andslower than files. Buffer with aBufferedReader or a BufferedInputStream.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    16/65

    Start any server (http server) onthe local machine

    Write a java program to readinformation sent from a httpserver and display on theconsole (http servers send HTML

    files)

    Eg: urldemo.java

    URL Demo Example

  • 8/2/2019 Java Networking by Kamalakar Dandu

    17/65

    Can send output as well as readinput

    Can post data to CGIs

    Can read headers from a

    connection

    URLConnection Vs URLs

  • 8/2/2019 Java Networking by Kamalakar Dandu

    18/65

    The java.net.URLConnection class is anabstract class that handlescommunication with different kinds ofservers like ftp servers and web servers.

    Protocol specific subclasses ofURLConnection handle different kinds ofservers.

    By default, connections to HTTP URLsuse the GET method(class:HTTPURLConnection).

    URL Connections

  • 8/2/2019 Java Networking by Kamalakar Dandu

    19/65

    1. The URL is constructed.

    2. The URLs openConnection() methodcreates the URLConnection object.

    3. The parameters for the connection andthe request properties that the clientsends to the server are set up.

    4. The connect() method makes theconnection to the server.

    5. The response header information is read

    using getHeaderField().

    Steps to URLConn..

  • 8/2/2019 Java Networking by Kamalakar Dandu

    20/65

    URLConnection//no constructorsObject getContent()String getHeaderField(String)/ (int)

    String getHeaderFieldKey(int)InputStream getInputStream()OututStream getOutputStream()String getContentEncoding()

    String getContentLength()/ getContentType()long getDate()/ getLastModified()long getExpiration()// expiration date of resource; 0 if unknown

    class Namepublic

    methods

    Class URL Connection

  • 8/2/2019 Java Networking by Kamalakar Dandu

    21/65

    Start any server (http server) onthe local machine

    Write a java program that opensa URLConnection to the server,reads and displays the header

    information (content type/length.)

    Eg: urlconndemo.java

    URLConn. Example

  • 8/2/2019 Java Networking by Kamalakar Dandu

    22/65

    Data may be read from theconnection in one of two ways

    raw by using the input stream

    returned bygetInputStream()

    through a content handler with

    getContent(). Data can be sent to the server

    using the output stream

    provided by getOutputStream().

    I / OURLConn.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    23/65

    Start any server (http server) onthe local machine

    Connect to a the server, readdata from the server usinggetContent() methods (shows

    how one can read header andother info throughURLConnection)

    Eg: UrlConnDemoReadFromServer.java

    Read - Example

  • 8/2/2019 Java Networking by Kamalakar Dandu

    24/65

    Start any server (http server) onthe local machine

    Connect to a the server, send arequest in the http protocolformat. After sending the request

    read from the server theinformation sent from the server,and display the information on

    the screen.

    Eg: UrlConnDemoReadWriteServer.java

    Read Write Example

  • 8/2/2019 Java Networking by Kamalakar Dandu

    25/65

    HTTP Protocol

    server

    client

    http://www.mcp.com/index.html

    GET /index.html HTTP/1.0

    HTTP/1.0 200 OKContent-type: text/html

    Content-Length: 128

    [ followed by the content

    information ]

    Protocol handlers implement the corresponding

    protocols

  • 8/2/2019 Java Networking by Kamalakar Dandu

    26/65

    The exact protocols that Javasupports vary from implementationto implementation though http and

    file are supported pretty mucheverywhere.

    file

    ftp gopher

    http

    mailto

    telnet

    doc

    netdoc

    verbatim

    jar

    Java Supported Protocol

  • 8/2/2019 Java Networking by Kamalakar Dandu

    27/65

    Data is sent across the Internetfrom one host to another is split

    into independent units of finitesize called packets / datagrams.

    They contain enough information to

    travel from source to destination They vary in size from a few

    dozen bytes to about 60,000

    bytes.

    Packets Vs Datagram

  • 8/2/2019 Java Networking by Kamalakar Dandu

    28/65

    TCP/IP protocol allows for errorcorrection

    If one packet is lost or has error,it can be retransmitted withoutrequiring redelivery of all other

    packets. If packets arrive out of order they

    can be reordered at the receiving

    end of the connection.

    Packets Allow Error Correction

  • 8/2/2019 Java Networking by Kamalakar Dandu

    29/65

    Sockets : Intro

    Working at different layers of thenetworking architecture (OSI Model)is time consuming and would wastethe effort of the programmer.

    Instead programmers are presentedwith an abstraction layer (socket) to

    communicate with servers/applications through the network.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    30/65

    What is a socket?

    Socket is a abstraction layer (aclass/object) that allows users(programmers) to communicate(read/write) through the network toremote hosts (servers)

    A socket can talk to a single porton the host(server)

    Sockets

  • 8/2/2019 Java Networking by Kamalakar Dandu

    31/65

    Sockets

    A socket is a reliable connection for thetransmission of data between two hosts.

    Sockets isolate programmers from the

    details of packet encodings, lost andretransmitted packets, and packets thatarrive out of order.

    There are limits. Sockets are more likely tothrow IOExceptions than files, for example.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    32/65

    Socket Operations

    There are four fundamental operations a socketperforms. These are:

    1. Connect to a remote machine.

    2. Send data.3. Receive data.

    4. Close the connection.

    A socket may not be connected to more than one

    host at a time.

    A socket may not reconnect after it's closed.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    33/65

    class Name

    public

    methods

    Socket Class

    Socket

    //constructorsSocket(String,int);

    Socket(InetAddress,int);

    Socket(String,int,InetAddress,int);

    Socket(InetAddress,int,InetAddress,int);

    Socket(String,int,boolean);// deprecated

    Socket(InetAddress,int,boolean); //deprecated

    Requirements for Socket constructors:

    Specify host as

    String or InetAddressSpecify port

    an integer between 1 and 65535

    All these constructors could throw IOException

    onnec on e ween en an

  • 8/2/2019 Java Networking by Kamalakar Dandu

    34/65

    server

    128

    0.

    Client

    Connection

    request

    Client

    server 12

    8

    0.

    1 2 80 .

    1280.

    Connection

    onnec on e ween en anServer

  • 8/2/2019 Java Networking by Kamalakar Dandu

    35/65

    Choosing a Local Port

    You can also specify a local portnumber,

    Setting the local port to 0 (last int) tellsthe system to randomly choose anavailable port.

    If you need to know the port you're

    connecting from, you can always get itwith getLocalPort().

    Socket s = new Socket(mysite.com", 80,

    mynewsite.com", 0);

  • 8/2/2019 Java Networking by Kamalakar Dandu

    36/65

    You cannot just connect to anyport on any host. The remote host

    must actually be listening forconnections on that port.

    You can use the constructors to

    determine which ports on a hostare listening for connections.

    Notes

    Eg:ListOfPorts.java

  • 8/2/2019 Java Networking by Kamalakar Dandu

    37/65

    clientserver

    Execute java applicationCreate a socket-returns if host found

    get handle to Outputstream

    write request to stream get handle for InputStream

    read data sent fromserver through stream

  • 8/2/2019 Java Networking by Kamalakar Dandu

    38/65

    Start any server (http server) on thelocal machine

    write a java program that opens a

    socket to the http server. Get anoutput stream and write inforequesting some html page (GET

    ). Then, open an inputstream andread the info sent from server intothe application.Eg: SocketReadWriteServer.java

    Socket s = new Socket(.);

    // s.getInputStream() returns handle to

    input stream and s.getOutputStream()

    returns handle to an output stream

    Socket Read Write Example

  • 8/2/2019 Java Networking by Kamalakar Dandu

    39/65

    Class Socket

    Socket//socket optionsvoid setTcpNoDelay(boolean on)boolean getTcpNoDelay()

    void setSoLinger(boolean on, int val)int getSoLinger()void setSoTimeout(int timeout)int getSoTimeout()InetAddress getInetAddress()

    InetAddress getLocalInetAddress()int getPort()int getLocalPort()String toString()

    class Namepublic

    methods

    throws SocketException

  • 8/2/2019 Java Networking by Kamalakar Dandu

    40/65

    Servers

    Servers are hosts that supply clients withinformation when requested

    Hence, they must be waiting for a clientrequest to arrive . The server then servesinfo to the client

    Many users (clients) may be reaching the

    server using the same protocol (port). Itmust be able to process and service them

    Java provides Server side sockets to

    enable programmers to write servers

  • 8/2/2019 Java Networking by Kamalakar Dandu

    41/65

    Server Sockets

    A server socket binds to a particularport on the local machine.

    Once it has successfully bound to a

    port, it listens for incomingconnection attempts.

    When a server detects a connection

    attempt, it accepts the connection.This creates a socket between theclient and the server over which theclient and the server communicate.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    42/65

    Class ServerSocket

    The ServerSocket class represents aserver socket.

    A ServerSocket object is constructed on a

    particular local port. Then it calls accept()to listen for incoming connections.

    accept() blocks until a connection is

    detected. Then accept() returns a Socketobject that performs the actualcommunication with the client.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    43/65

    Class ServerSocket

    class Name

    public

    methods

    Socket

    ServerSocket(int);ServerSocket(int,int);ServerSocket(int,int, InetAddress);InetAddress getInetAddress();int getLocalPort();Socket accept();void close();

    void setSoTimeout(int);int getSoTimeout();

    new ServerSocket(5000)

    will attempt to bind to the port 5000 on the

    machine on which the application is running

  • 8/2/2019 Java Networking by Kamalakar Dandu

    44/65

    Example

    Write a simple java server.

    Create a server socket on a port

    wait for connections in an infiniteloop

    if request comes, service the requestthat comes and continue waiting

    Eg:myServer.java

  • 8/2/2019 Java Networking by Kamalakar Dandu

    45/65

    Example

    Write a client.

    Create a socket connecting to themachine and port

    read the data from the server

    display data on the console

    Eg:myClient.java

  • 8/2/2019 Java Networking by Kamalakar Dandu

    46/65

    Notes ...

    No more than one process/ thread canlisten to a port at a time (including non-

    java processes / threads). If an http server is already running on port

    80, you cannot bind ServerSocket to port80.

    If such an attempt is made BindExceptionis generated.

    If the port parameter is 0. It tells java to

    pick an available port.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    47/65

    Adding Threading to a Server

    It's better to make your server multi-threaded.

    There should be a loop whichcontinually accepts new connections.

    Rather than handling the connection

    directly the socket should be passedto a Thread object that handles theconnection.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    48/65

    Multi-threading is a good thing but it's still not aperfect solution.

    Look at this accept loop:

    while (true) {try {

    Socket s = ss.accept();

    ThreadedServer ts = new ThreadedServer(s) ;

    ts.start(); // run method of Thread sends data

    }

    catch (IOException e) {}

  • 8/2/2019 Java Networking by Kamalakar Dandu

    49/65

    Every time you pass through this loop, a newthread gets created. Every time a connection isfinished the thread is disposed of.

    Spawning a new thread for each connectiontakes a non-trivial amount of time, especiallyon a heavily loaded server. It would be betternot to spawn so many threads.

    One solution is to create a thread pool, anduse them from a thread

  • 8/2/2019 Java Networking by Kamalakar Dandu

    50/65

    UDP

    User Datagram protocol

    Packet oriented, not stream oriented likeTCP/IP

    Much faster but no error correction (hencesome times called as unreliable protocol)

    NFS, TFTP, and FSP use UDP/IP

    Must fit data into packets of about 8K or lessas the protocol unlike the TCP will not do itfor you

  • 8/2/2019 Java Networking by Kamalakar Dandu

    51/65

    The UDP Classes

    Java's support for UDP iscontained in two classes:

    java.net.DatagramSocket.

    java.net.DatagramPacket.

    A Datagram socket is used tosend and receive Datagrampackets.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    52/65

    java.net.DatagramPacket

    A wrapper for an array of bytesfrom which data will be sent or

    into which data will be received.

    Also contains the address andport to which the packet will besent.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    53/65

    java.net.DatagramSocket

    A DatagramSocket object is a localconnection to a port that does the sendingand receiving.

    There is no distinction between a UDP socket

    and a UDP server socket. Also unlike TCP sockets, a DatagramSocket

    can send to multiple, different addresses.

    The address to which data goes isstored inthe packet, not in the socket.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    54/65

    UDP Ports

    Separate from TCP ports.

    Each computer has 65,536 UDPports as well as its 65,536 TCPports.

    A server socket can be bound toTCP port 20 at the same time as adatagram socket is bound to UDP

    port 20.

    Class DatagramPacket

  • 8/2/2019 Java Networking by Kamalakar Dandu

    55/65

    Class DatagramPacket

    DatagramPacket

    DatagramPacket(byte[], int)DatagramPacket(byte[], int, InetAddress, int)void setAddress(InetAddress)

    void setPort(int )void setData(byte [])void setLength(int )InetAddress getAddress()

    int getPort()byte[] getData()int getLength()

    class Name

    public

    methods

    First constructor for receiving data, and

    second for sending to a specific address

  • 8/2/2019 Java Networking by Kamalakar Dandu

    56/65

    Example

    String s = "My first UDP Packet"

    byte[] b = s.getBytes();

    DatagramPacket dp = newDatagramPacket

    (b, b.length);

    Wi h D i i

  • 8/2/2019 Java Networking by Kamalakar Dandu

    57/65

    With a Destination

    try {InetAddress inetadd = new InetAddess(localhost");

    int chargen = 19;

    String s = "My second UDP Packet"

    byte[] b = s.getBytes();

    DatagramPacket dp = new DatagramPacket(b,b.length, inetadd, chargen);

    }

    catch (UnknownHostException e) {

    System.out.println(e);

    }

    Class DatagramSocket

  • 8/2/2019 Java Networking by Kamalakar Dandu

    58/65

    Class DatagramSocket

    DatagramSocket

    DatagramSocket()DatagramSocket(int)DatagramSocket(int, InetAddress )

    void send(DatagramPacket);void receive(DatagramPacket);InetAddress getLocalAddress();getLocalPort();

    void setSoTimeout(int);int getSoTimeout();void close();

    class Name

    public

    methods

    First constructor for clients, and second two

    are for servers specifying a port / host address

  • 8/2/2019 Java Networking by Kamalakar Dandu

    59/65

    Sending UDP Datagrams

    To send data to a particular server.

    Convert the data into byte array.

    Pass this byte array, the length of the datain the array (most of the time this will be thelength of the array) and the InetAddress andport to which you wish to send it into the

    DatagramPacket() constructor. Next create a DatagramSocket and pass the

    packet to its send() method.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    60/65

    Receiving UDP Datagrams

    Construct a DatagramSocket object onthe port on which you want to listen.

    Pass an empty DatagramPacket objectto the DatagramSocketsreceive()method.

    public synchronized void receive(DatagramPacket

    dp) throws IOException.

    The calling thread blocks until aDatagram is received.

  • 8/2/2019 Java Networking by Kamalakar Dandu

    61/65

    DatagramPacket dp is filled with the datafrom that datagram.

    Use getPort() and getAddress() to tell where

    the packet came from, use getData() to retrieve the data, and

    use getLength() to see how many bytes werein the data.

    If the received packet was too long for thebuffer, it's truncated to the length of thebuffer.

    Example

  • 8/2/2019 Java Networking by Kamalakar Dandu

    62/65

    Exampletry {byte buffer = new byte[65536];DatagramPacket incoming = newDatagramPacket(buffer, buffer.length);DatagramSocket ds = newDatagramSocket(2134);

    ds.receive(incoming);byte[] data = incoming.getData();String s = new String(data, 0,data.getLength());System.out.println("Port " +

    incoming.getPort() + " on " +incoming.getAddress() + " sent thismessage:");System.out.println(s);

    }

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

    Example

  • 8/2/2019 Java Networking by Kamalakar Dandu

    63/65

    Example

    Write a simple java UDP SERVER

    Create a server socket on a port

    wait for connections in an infiniteloop

    if request comes, read the information,and send it back to the client.

    Eg: UDPServer.java

    Example

  • 8/2/2019 Java Networking by Kamalakar Dandu

    64/65

    Example

    Write a UDP client.

    Create a socket connecting to the

    machine and port Send data to the server

    Read the info sent back from the

    serverEg: UDPClient.java

  • 8/2/2019 Java Networking by Kamalakar Dandu

    65/65

    Exercise (contd)

    18. This works fine on the same localmachine but the data is needed to beaccessed across the network so that the

    data/information can be shared. Developthe appropriate socket interfaces andmake the information available across the

    network.