Java Networking pdf

download Java Networking pdf

of 40

Transcript of Java Networking pdf

  • 7/28/2019 Java Networking pdf

    1/40

    NETWORKINGIN

    JAVA

  • 7/28/2019 Java Networking pdf

    2/40

    INTRODUCTION

    One of the biggest secrets about Java is that it makeswriting network programs easy.

    In fact, it is far easier to write network programs inJava than in almost any other language.

    Major applications have some level of networking built

    in.

    IDEs like Eclipse and NetBeans communicate withCVS and SVN repositories.

  • 7/28/2019 Java Networking pdf

    3/40

    CONTINUE..

    Antivirus programs like Norton Antivirus check fornew virus definitions by connecting to the vendor's website every time the computer is started.

    It is easy for Java applications to send and receivedata across the Internet. Easy in terms of the processthat we have to follow to transmit data over a network.

  • 7/28/2019 Java Networking pdf

    4/40

    WHATYOUCANDOWITHN/WPROGRAMMING ?

    Networking adds a lot of power to simple programs.With network programming, a single program canretrieve information stored in millions of computers

    and of course located anywhere in the world. A singleprogram can communicate with millions of people.

    Network applications are having several forms. Themost common is between clients and servers. In the

    simplest case, clients retrieve data from a server anddisplay it.

    More complex clients filter and reorganize data,

  • 7/28/2019 Java Networking pdf

    5/40

    repeatedly retrieve changing data, send data to otherpeople and computers, and can interact with peers inreal time for chat, multiplayer games.

    Simple servers merely look up some file and return itto the client, but more complex servers often do a lot ofprocessing on the data before answering an involvedquestion. Let's look more closely at the possibilities

    that open up when you add networking to yourprograms.

  • 7/28/2019 Java Networking pdf

    6/40

    BASIC NETWORKCONCEPTS

    A network is a collection of computers and otherdevices that can send data to and receive data fromeach other, more or less in real time. A network is

    often connected by wires or wireless.

    Each machine on a network is called a node and nodesthat are fully functional computers are also called

    hosts.

    Every node in network has an address, that uniquelyidentify it.

  • 7/28/2019 Java Networking pdf

    7/40

    TCP/IPAND UDP

    TCP/IPIt is reliable protocol.

    Data sent using this protocol will be guaranteed to bedelivered. Also order of the packet will remain same.

    UDPIt is unreliable protocol. Data sent using thisprotocol will not guaranteed to be delivered. Also orderof the packet may be same or it may change. This

    protocol is faster then TCP/IP.

  • 7/28/2019 Java Networking pdf

    8/40

    WHATIS IP ADDRESSAND HOSTNAME

    As a Java programmer we should not worry aboutinternals of IP address but we should know about howto address IP.

    On IPV4 host is defined by four-byte numbersomething like 192.168.250.1

    So when we sent data over a network header of thepacket will include destination address and sourceaddress in form of IP address.

  • 7/28/2019 Java Networking pdf

    9/40

    PORT

    If you want to do more than one thing at a time over anetwork then ports will be required.

    Every computer with IP address has several thousandlogical ports infact 65,535 to be precise.

    They do not exists physically remember they are justabstraction.

    Each port can be identified with number ranges from 1to 65535.

  • 7/28/2019 Java Networking pdf

    10/40

    REMEMBER : Port numbers between 1 and 1,023 are

    reserved for some predefined services.

    Some well known ports and service running under it.PORT PROTOCOL DESCRIPTION

    21 FTP You can send FTP command via this service.

    80 HTTP Protocol used by World Wide Web.

    25 SMTP Protocol used for sending email betweensystems.

    110 POP3 Transfer emails from host to clients.

    1099 RMI REGISTRY Registry service for Java remote objects.

  • 7/28/2019 Java Networking pdf

    11/40

    INTERNET !!!!

    It is worlds one of the largest IP based network. Eachcomputer on this network is identified with unique IPaddress.

    Another popular network is Intranet, this kind ofnetwork is not connected to Internet but they put datain some internal web server.

  • 7/28/2019 Java Networking pdf

    12/40

    I/O STREAMS

    Many network program will deal with simple inputand output means transferring bytes from one system

    to another system.

    In Java I/O works with streams. Input streams areused to read data and output streams are used to write

    data

  • 7/28/2019 Java Networking pdf

    13/40

    INTERNETADDRESS CLASS

    Now we know each computer or host on network isidentified by unique IP address.

    But if we see IP address it is always hard to rememberright ?

    For solution of above problem internet designers comeup with Domain Name System (DNS).

    Any DNS will be associated with HOSTNAME that wecan remember Like (www.google.com) and IP addressthat computer can remember.

  • 7/28/2019 Java Networking pdf

    14/40

    Class java.net.InetAddress is Java's high-level

    representation of an IP address for both IPv4 and IPv6.

    We will use this class with Socket, ServerSocket,

    DatagramSocket, MulticastSocket classes.

    We can use both a hostname and an IP address in thisclass.

    Using InetAddress Objects via three methods.

  • 7/28/2019 Java Networking pdf

    15/40

    public static InetAddress getByName(String hostName)

    throws UnknownHostException

    public static InetAddress[] getAllByName(String

    hostName) throws UnknownHostException

    public static InetAddress getLocalHost() throws

    UnknownHostException

  • 7/28/2019 Java Networking pdf

    16/40

    SOCKETSFOR CLIENTS

    On internet data will be transferred in packets of finite sizecalled datagrams.

    Each datagram contains a header and a payload. The headercontains the address and port to which the packet is going,the address and port from which the packet came, andvarious other information used to ensure reliabletransmission. And payload contains the data itself.

    It is also possible that one or more packets may be lost orcorrupted in transmission and need to be retransmitted.

  • 7/28/2019 Java Networking pdf

    17/40

    Keeping track of this - splitting the data into packets,

    generating headers, parsing the headers of incoming

    packets, keeping track of what packets have and haven't

    been received, and so on - is a lot of work and requires a

    lot of intricate code.

    We do not have to worry about above things. Socketsshield the programmer error detection, packet sizes,

    packet retransmission, network addresses and more

  • 7/28/2019 Java Networking pdf

    18/40

    SOWHATIS SOCKET ?

    A socket is a connection between two hosts. It canperform few operations.

    Connect to a remote machineSend data

    Receive data

    Close a connection

    Bind to a portListen for incoming data

    Accept connections from remote machines on the boundport

  • 7/28/2019 Java Networking pdf

    19/40

    Java program will require to use Client Socket via

    following way.

    Create a new Socket using constructor.

    Socket will try to connect to remote host.

    Once the connection is established, the local and remotehosts get input and output streams from the socket anduse those streams to send data to each other. Thisconnection is full-duplex. Both hosts can send and receivedata simultaneously.

  • 7/28/2019 Java Networking pdf

    20/40

    The java.net.Socket class is Java's fundamental class

    for performing client-side TCP operations.

    To create Client socket call constructor of Socket class.

    public Socket(String host, int port) throwsUnknownHostException, IOException

    This constructor creates a TCP socket to the specifiedport with specified host and attempts to connect to thehost.`

  • 7/28/2019 Java Networking pdf

    21/40

    SOCKETFOR SERVER.

    For servers to accept connections, Java provides ajava.net.ServerSocket class that represents server sockets.Actually server socket's job is to wait for incoming

    connection.

    ServerSocket will listen for incoming TCP connections.

    When a client on any host attempts to connect to thatport, the server will negotiates with the connection andreturns a regular Socket object representing the socketbetween the two hosts.

  • 7/28/2019 Java Networking pdf

    22/40

    Once a ServerSocket has set up the connection, theserver uses a regular Socket object to send data to theclient.

    You can create a server socket via following constructors,there are four public ServerSocket constructors

    public ServerSocket(int port) throws BindException,IOException

    This constructor creates a server socket on the portspecified in the argument. If you pass 0 for the portnumber, the system selects an available port for you.

  • 7/28/2019 Java Networking pdf

    23/40

    public ServerSocket(int port, int queueLength) throws

    BindException, IOException

    This constructor opens a server socket on the specified portwith a queue length of your choosing.queue length is how

    many requires you want to keep in queue after that server

    will refuse the connection.

  • 7/28/2019 Java Networking pdf

    24/40

    public ServerSocket(int port, int queueLength, InetAddress

    bindAddress) throws IOException

    The only difference in this constructor is to listen on specific

    address.

    public ServerSocket( ) throws IOException

    Create a ServerSocket object but does not actually bind it to

    any port, So it cannot initially accept any connections. Later

    on you have to call bind() methods.

  • 7/28/2019 Java Networking pdf

    25/40

    UDP DATAGRAMSAND SOCKETS

    TCP is designed for reliable transmission of data. If by anycase data is lost or damaged during transmission, TCP willresent data. Also if packets of data arrive out of order, TCPputs them back in the correct order; if the data is coming

    too fast for the connection, TCP adjust the speed sopackets won't be lost.

    Moral of the story is a program never needs to worry aboutreceiving data that is out of order or incorrect if it uses

    TCP.

    However, this reliability comes at a price. That price isspeed. Establishing and tearing down TCP connections can

  • 7/28/2019 Java Networking pdf

    26/40

    take a fair amount of time, particularly for protocols such

    as HTTP, which tend to require many short transmissions.

    The User Datagram Protocol (UDP) is an alternative

    protocol for sending data over IP that is very quick.

    Unfortunately it is not reliable. When you send UDP data,you have no way of knowing whether it arrived, also data

    arrived in the order in which you sent them.

    However, the pieces that do arrive generally arrivequickly.

  • 7/28/2019 Java Networking pdf

    27/40

    Java's implements UDP into two classes:

    DatagramPacket and DatagramSocket.

    The DatagramPacket class package bytes of data intoUDP packets called datagrams and lets you unpackagedatagrams that you receive.

    A DatagramSocket sends as well as receives UDPdatagrams.

  • 7/28/2019 Java Networking pdf

    28/40

    To send data, you put the data in a DatagramPacket andsend the packet using a DatagramSocket. To receivedata, you receive a DatagramPacket object from a

    DatagramSocket and then read the contents of thepacket.

    In UDP, the address to which it is directed, is includedin the packet itself. the socket only needs to know the

    local port on which to listen or send.

  • 7/28/2019 Java Networking pdf

    29/40

    DATAGRAMPACKET CLASS

    DatagramPacket uses different constructors dependingon whether the packet will be used to send data or toreceive data.

    Constructors for sending datagrams

    public DatagramPacket(byte[] buffer, int length)

    public DatagramPacket(byte[] buffer, int offset, intlength)

  • 7/28/2019 Java Networking pdf

    30/40

    DatagramPacket uses different constructors depending

    on whether the packet will be used to send data or toreceive data.

    Constructors for sending datagrams

    public DatagramPacket(byte[] buffer, int length)

    public DatagramPacket(byte[] buffer, int offset, intlength)

  • 7/28/2019 Java Networking pdf

    31/40

    When a socket receives a datagram, it stores the

    datagram's data part in buffer beginning at buffer[0]and continuing until the packet is completely stored oruntil length bytes have been written into the buffer. If

    the second constructor is used, storage begins atbuffer[offset] instead. Otherwise, these twoconstructors are identical.

  • 7/28/2019 Java Networking pdf

    32/40

    CONSTRUCTORSFORSENDINGDATAGRAMS

    public DatagramPacket(byte[] data, int length,InetAddress

    destination, int port)

    public DatagramPacket(byte[] data,int offset,intlength,InetAddress destination, int port)

    public DatagramPacket(byte[] data, int length, SocketAddress

    destination, int port)

    public DatagramPacket(byte[] data, int offset, int

    length,SocketAddress destination, int port)

  • 7/28/2019 Java Networking pdf

    33/40

    Each constructor creates a new DatagramPacket to be

    sent to another host. The packet is filled with lengthbytes of the data array starting at offset or 0 if offset isnot used.

  • 7/28/2019 Java Networking pdf

    34/40

    DATAGRAMSOCKET CLASS

    To send or receive a DatagramPacket, you must open adatagram socket. In Java, a datagram socket is createdand accessed through the DatagramSocket class.

    Following are the constructors.

    public DatagramSocket( ) throws SocketException

    This constructor creates a socket that is bound to ananonymous port

  • 7/28/2019 Java Networking pdf

    35/40

    public DatagramSocket(int port) throws

    SocketException

    This constructor creates a socket that listens forincoming datagrams on a particular port.

  • 7/28/2019 Java Networking pdf

    36/40

    MULTICAST SOCKETS

    The sockets that we have seen so far are unicast: theyprovide point-to-point communication. Unicast socketscreate a connection with two well-defined endpoints.there is one sender and one receiver and, although theymay switch roles, at any given time it is easy to tell whichis which.

    However, although point-to-point communications serve

    many, if not most needs, many tasks require a differentmodel. For example, a television station broadcasts datafrom one location to every point within range of itstransmitter.

  • 7/28/2019 Java Networking pdf

    37/40

    The signal reaches every television set, whether or not it's

    turned on and whether or not it's tuned to that particular

    station.

    Multicasting is broader than unicast, point-to-point

    communication but narrower and more targeted than

    broadcast communication. Multicasting sends data from

    one host to many different hosts, but not to everyone. the

    data only goes to clients that have expressed an interest byjoining a particular multicast group.

  • 7/28/2019 Java Networking pdf

    38/40

  • 7/28/2019 Java Networking pdf

    39/40

    To receive data that is being multicast from a remote

    site, first create a MulticastSocket with theMulticastSocket( ) constructor. Next, join a multicastgroup using the MulticastSocket's joinGroup( ) method.

    Once you've joined the multicast group, you receive UDPdata just as you would with a DatagramSocket.

  • 7/28/2019 Java Networking pdf

    40/40

    QUESTION ?