SlideShare une entreprise Scribd logo
1  sur  9
Télécharger pour lire hors ligne
Java – Networking Theory                                   Page 1



                                       Java – Networking
                                            Theory
Socket Basics
In client-server applications, the server provides some service, such as processing database queries or sending
out web pages. The client uses the service provided by the server, either displaying database query results to
the user or displaying the web page in a browser. The communication that occurs between the client and the
server must be reliable. That is, no data can be dropped and it must arrive on the client side in the same order
in which the server sent it.

TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet
use to communicate with each other. To communicate over TCP, a client program and a server program
establish a connection to one another. Each program binds a socket to its end of the connection. To
communicate, the client and the server each reads from and writes to the socket bound to the connection.

What Is a Socket?
A socket is one end-point of a two-way communication link between two programs running on the network.

A socket is a connection between two hosts. It can perform seven basic operations:
1. Connect to a remote machine
2. Send data
3. Receive data
4. Close a connection
5. Bind to a port
6. Listen for incoming data
7. Accept connections from remote machines on the bound port

The java.net package provides two classes--Socket and ServerSocket--that implement the client
side of the connection and the server side of the connection, respectively.

The Socket Class
1. The java.net.Socket class is used for performing client-side TCP operations. Other client-
   oriented classes that make TCP network connections, such as URL, and URLConnection all
   ultimately end up invoking the methods of this class.
2. The methods of the Socket class set up and tear down connections and set as various socket
   options.
3. Because TCP sockets are more or less reliable connections, the interface that the Socket class
   provides to the programmer is streams. The actual reading and writing of data over the socket is
   accomplished via stream classes.
4. Java's Socket class, which is used by both clients and servers, has methods that correspond to the
   first four of the seven operations stated above. [The last three operations are needed only by
   servers, which wait for clients to connect to them. They are implemented by the ServerSocket
   class].
5. Constructors of the Socket class:
   a) public Socket (String host, int port)
        This connects a TCP socket to the given host and port.



mukeshtekwani@hotmail.com                                                          Prof. Mukesh N. Tekwani
2                                     Java – Networking Theory


       Example of use of Socket constructor:
       try
       {
            Socket s = new Socket("www.google.com", 80);
            // send and receive data...
       }
       catch (UnknownHostException e)
       {
            System.err.println(e);
       }
       catch (IOException e)
       {
            System.err.println(e);
       }

    b) public Socket(InetAddress host, int port) throws IOException
       This constructor creates a TCP socket to the specified port on the specified host and tries to
       connect. It differs from the previous constructor in that it uses an InetAddress object to
       specify the host instead of a hostname. It throws an IOException if it can't connect, but does
       not throw an UnknownHostException; if the host is unknown, you will find out when you
       create the InetAddress object.

       Example:

       try
       {
               InetAddress iadd =            InetAddress.getByName("www.google.com");

               Socket s = new Socket(iadd, 80);
               // send and receive data...
       }
       catch (UnknownHostException e)
       {
            System.err.println(e);
       }
       catch (IOException e)
       {
            System.err.println(e);
       }

6. Other methods of Socket class:
   a) Socket() – creates a socket that has not yet been initialized.
   b) void connect(SocketAddress add) - connects the socket to the given address
   c) void connect(SocketAddress add, int timeoutInMillisecs) –
      connects the socket to the given address or returns if the time interval expired.
   d) void setTimeout(int timeoutMillisecs) - sets the blocking time for read
      requests on the socket. When the time out is reached, the InterruptedIOException is raised.
   e) boolean isConnected() – returns true if the socket is connected
   f) boolean isClosed() – returns true if the socket is closed.


Prof. Mukesh N Tekwani                                               mukeshtekwani@hotmail.com
Java - Networking                                 Page 3


7. Java programs use client sockets in the following fashion:
   a) The program creates a new socket with a Socket( ) constructor.
   b) The socket attempts to connect to the remote host.
   c) Once the connection is established, the local and remote hosts get input and output streams
      from the socket and use those streams to send data to each other. This connection is full-
      duplex; both hosts can send and receive data simultaneously. What the data means depends
      on the protocol; different commands are sent to an FTP server than to an HTTP server. There
      will normally be some agreed-upon hand-shaking followed by the transmission of data from
      one to the other.
   d) When the transmission of data is complete, one or both sides close the connection. Some
      protocols, such as HTTP 1.0, require the connection to be closed after each request is
      serviced. Others, such as FTP, allow multiple requests to be processed in a single connection.


The ServerSocket class:
1. The ServerSocket class contains everything you need to write servers in Java.
2. It has constructors that create new ServerSocket objects, methods that listen for connections on a
   specified port, and methods that return a Socket object when a connection is made so that you
   can send and receive data.

The basic life cycle of a server socket is:
1. A new ServerSocket is created on a particular port using a ServerSocket( ) constructor.
2. The ServerSocket listens for incoming connection on that port using its accept( ) method. When
   the client connects to the server, accept( ) method returns a Socket object connecting the client
   and the server.
3. Depending on the type of server, either the Socket's getInputStream() method,
   getOutputStream( ) method, or both are called to get input and output streams that communicate
   with the client.
4. The server and the client interact according to an agreed-upon protocol until it is time to close
   the connection.
5. The server, the client, or both close the connection.
6. The server returns to step 2 and waits for the next connection.

If step 4 is likely to take a long or indefinite amount of time, certain servers create a new process to
handle each connection so that multiple clients can be serviced at the same time. Java programs
should spawn a thread to interact with the client so that the server can be ready to process the next
connection sooner.

Constructors of the ServerSocket class:
1. public ServerSocket(int port) throws IOException, BindException
      This constructor creates a server socket on the port specified by the argument. If you don’t
      pass the port number, the system selects an available port for you. A port chosen for you by
      the system is sometimes called an anonymous port since you don't know its number.

2. public ServerSocket(int port, int queueLength) throws IOException,
   BindException
      This constructor creates a ServerSocket on the specified port with a queue length of your
      choosing. The queueLength argument sets the length of the queue for incoming connection
      requests — that is, howmany incoming connections can be stored at one time before the
      host starts refusing connections. Some operating systems have a maximum queue length,
mukeshtekwani@hotmail.com                                                    Prof. Mukesh N. Tekwani
4                                     Java – Networking Theory


       typically five. For example, to create a server socket on port 5776 that would hold up to 100
       incoming connection requests in the queue, you would write:

       try
       {
               ServerSocket httpd = new ServerSocket(5776, 100);
       }
       catch (IOException e)
       {
               System.err.println(e);
       }
       The constructor throws a BindException if the socket cannot be created and bound to the
       requested port. An IOException means that the port is already in use.

3. public ServerSocket(int port, int queueLength, InetAddress
   bindAddress) throws IOException
   • This constructor creates a ServerSocket on the specified port with the specified queue length.
      This ServerSocket binds only to the specified local IP address.
   • This constructor is useful for servers that run on systems with several IP addresses because it
      allows you to choose the address to which you'll listen. That is, this ServerSocket listens only
      for incoming connections on the specified address; it won't listen for connections that come
      in through the host's other addresses. The other constructors bind to all local IP addresses by
      default.

Other methods of the ServerSocket class:
Socket accept() –
       A ServerSocket generally operates in a loop that repeatedly accepts connections. Each pass
       through the loop invokes the accept() method. This method blocks (stops the flow of
       execution) the current thread until the connection is made. The method returns a Socket
       object through which the program can communicate with the client.

void close() –
       Closes the server socket an stop processing any further requests.


Internet Addresses:
1. Internet addresses are numerical addresses that consist of 4 bytes in IPv4 (or 16 bytes in IPv6).
2. These addresses are written as a dotted quad like this: 132.163.4.102. Each of these quads can
   vary from 0 to 255.
3. When your browser requests a web page from another computer on the Internet, it automatically
   sends your computer’s address where the server should send the web page. This is called your
   computer’s IP address.
4. It is easier for human beings to deal with host names such as www.google.com instead of the
   numeric IP addresses.
5. IP address can be static or dynamic. A static IP address is a fixed address and cannot be changed.
   A dynamic IP address changes every time the user connects to the Internet.
6. The java.net package supports IPv6 addresses provided the host computer’s OS supports these
   addresses.

Prof. Mukesh N Tekwani                                               mukeshtekwani@hotmail.com
Java - Networking                               Page 5


7. The java.net package has the InetAddress class to convert between host names and Internet
   addresses.
8. Methods of InetAddress class:
   a) public static InetAddress getByName(String host) throws
      UnknownHostException – this method determines the IP address of a host if the host
      name is given.
   b) static InetAddress [] getAllByName(String host) - constructs an array
      of an Internet addresses for the given host name
   c) static InetAddress getLocalHost() – constructs an InetAddress for the local
      host
   d) byte [] getAddress() – returns an array of bytes that contains numerical address.
   e) String getHostAddress() – returns a string with decimal numbers separated by
      periods, e.g., “132.163.4.102”
   f) String getHostName() – returns the host name



The URL
1. URL is the abbreviation of Uniform Resource Locator.
2. It is a reference or an address to a resource on the Internet (e.g., java.sun.com)
3. The URL is the address of a web page; each web page has its own unique address.
4. A URL can be split into 5 parts.
        Consider the URL http://www.somesite.com/dcn/chap1.html
        The 5 parts of the URL are as follows:
        (i)      http:// - stands for the protocol. The most common protocol is the HyperText
                 Transfer Protocol. Others are FTP and HTTPS (Secure).
        (ii)     www – This is the sub domain. Some sites use the sub domain ftp, news, etc.
        (iii) somesite.com – It is the host or domain name. www and the domain name combined
                 together give the IP address. Thus, www.somesite.com can be replaced by an IP
                 address.
        (iv)     dcn – It is a folder or directory and all files are stored in this directory.
        (v)      chap1.html - It is the file which is fetched from the server. If a filename is not
                 specified, the default file is index.html
5. The URL class
        The URL class has the following constructors:
        a) URL (String str) - Creates a URL object from the specified string
        b) URL(URL baseurl, String relativeurl);
        c) URL(String protocol, String host, int port, String file) – Creates a URL object from the
             specified protocol, host, port number and file.
        d) URL(String protocol, String host, String file) – Creates a URL from the specified
             protocol, hostname and file name.
        e) The URL object can be constructed like this:
                 URL add = new URL(http://www.dnaindia.com);
                 Such a URL is called an absolute URL. It contains all the information necessary to
                 reach the resource

              We can also create a relative URL which contains just enough information to reach
              the resource relative to another URL.



mukeshtekwani@hotmail.com                                                Prof. Mukesh N. Tekwani
6                                    Java – Networking Theory


              Example: Consider the base URL http://www.somesite.com/pages Suppose the pages
              on this site are page1.html and page2.html. We can create URL objects for these
              pages relative to their common base URL like this:

              URL add = new URL(“http://www.somesite.com/pages”);
              URL pg1url = new URL(add, “page1.html”);
              URL pg2url = new URL(add, “page2.html”);


[Ref Program 2 in Java Networking Programs notes]


The URLConnection Class
1. The abstract class URLConnection is the superclass of all classes that represent a
   communications link between the application and a URL.
2. Instances of this class can be used both to read from and to write to the resource referenced by
   the URL.
3. Creating a connection to a URL requires these steps:
      i.  The connection object is created by invoking the openConnection method on a URL.
     ii.  The setup parameters and general request properties are manipulated.
    iii. The actual connection to the remote object is made, using the connect method.
    iv.   The remote object becomes available. The header fields and the contents of the remote
          object can be accessed.
4. The following methods are used to access the header fields and the contents after the connection
   is made to the remote object:
   • getContent() -                  Retrieves the contents of this URL connection.
   • getHeaderField() -              Returns the value of the named header field.
   • getInputStream() -              Returns an input stream that reads from this open connection.
   • getOutputStream() -             Returns an output stream that writes to this connection.
5. Certain header fields are accessed frequently. These are:
   • getContentEncoding -            Returns the value of the content-encoding header field.
   • getContentLength -              Returns the value of the content-length header field.
   • getContentType -                Returns the value of the content-type header field.
   • getDate -                       Returns the value of the date header field.
   • getExpiration -                 Returns the value of the expires header field.
   • getLastModifed –                Returns the last modified date


Serving Multiple Clients
1. A typical server runs on a server computer and clients from all over the Internet might want to
   use the server at the same time. The server must be able to accept incoming requests from more
   than one client at a time. This can be done by using threaded programs in Java.
2. Evert time a program has established a new socket connection we will launch a new thread to
   take care of the connection between the server and that client.
3. The main program will go back and wait for the next connection.
4. Thus, we have to create a loop on the server as follows:




Prof. Mukesh N Tekwani                                             mukeshtekwani@hotmail.com
Java - Networking                               Page 7


      while(true)
      {
              Socket incoming = s.accept();
              Runnable r = new ThreadedEchoHandler(incoming);

             Thread t = new Thread(r);
             t.start();
      }

      The ThreadedEchoHandler class implements the Runnable interface and contains the loop
      with the client in its run method.

      class ThreadedEchoHandler implements Runnable
      {
           …
           public void run()
           {
                try
                {
                     Inputstream inps = incoming.getInputStream();
                     OutputStream outs = incoming.getOutputStream();

                            //Process input and send response
                            incoming.close();
                    }
                    catch(Exception ex)
                    {
                         Handle exception
                    }
             }
      }

      Since each connection starts a new thread, multiple clients can connect to the server at the
      same time.

Sending E-Mail
1.    A socket program can be used to send email.
2.    To send an email, we have to make a socket connection to port 25 which is the SMTP
      port (SMTP= Simple Mail Transfer Protocol). The SMTP describes the format for email
      messages.
3.    Steps are as follows:
        i.   Open a socket to the host system
             Socket s = new Socket(“mail.yourserver.com”, 25);          // 25 is for SMTP
             PrintWriter out = new PrintWriter(s.getOutputStream());
             [PrintWriter class is used to format representations of objects to a text-output
             stream. Import the package java.io.Writer for this class.]
       ii. Send the following information to the print stream:
             HELO sending host
             MAIL FROM: <sender e-mail address>

mukeshtekwani@hotmail.com                                               Prof. Mukesh N. Tekwani
8                                         Java – Networking Theory


                RCPT TO : <recipient e-mail address>
                DATA
                mail message
                (any number of lines)

                QUIT

                The SMTP specification requires that all lines must be terminated with r followed
                by n.


Understanding Ports
Generally speaking, a computer has a single physical connection to the network. All data destined for a
particular computer arrives through that connection. However, the data may be intended for different
applications running on the computer. So how does the computer know to which application to forward the
data? Through the use of ports.

Data transmitted over the Internet is accompanied by addressing information that identifies the computer and
the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver
data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use
to deliver the data to the right application.

In connection-based communication such as TCP, a server application binds a socket to a specific port
number. This has the effect of registering the server with the system to receive all data destined for that port.
A client can then rendezvous with the server at the server's port, as illustrated here:




Definition: The TCP and UDP protocols use ports to map incoming data to a particular process
running on a computer.

In datagram-based communication such as UDP, the datagram packet contains the port number of its
destination and UDP routes the packet to the appropriate application, as illustrated in this figure:




Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers
ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP
and other system services. These ports are called well-known ports. Your applications should not attempt to
bind to them.

Prof. Mukesh N Tekwani                                                       mukeshtekwani@hotmail.com
Java - Networking                              Page 9



IMPORTANT QUESTIONS
1.  Explain the terms socket and port.
2.  How can you get the IP address of a machine from its host name?
3.  How can you find out the current IP address of your computer?
4.  What is ServerSocket and how is it used?
5.  Network server programs are often multithreaded. Explain what this means and why it is true.
6.  Using the URL class, write a program to retrieve the file
    http://www.timesofindia.com/index.html and return the last modified date of this page.
7. Explain the URL class.
8. Explain the URLConnection class
9. Explain the following methods of the URL class: getHost(), getPort(), getProtocol()
10. How can DatagramSocket and DatagramPacket be used to send information across two
    computers in a network?
11. Write a Java program to accept a URL from the command line. If it uses the HTTP protocol then
    find the length of its contents.




mukeshtekwani@hotmail.com                                               Prof. Mukesh N. Tekwani

Contenu connexe

Tendances

Java Network Programming
Java Network ProgrammingJava Network Programming
Java Network Programmingbackdoor
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programmingashok hirpara
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)UC San Diego
 
Java API: java.net.InetAddress
Java API: java.net.InetAddressJava API: java.net.InetAddress
Java API: java.net.InetAddressSayak Sarkar
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In JavaAnkur Agrawal
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in JavaTushar B Kute
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket ProgrammingVipin Yadav
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Javasuraj pandey
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programmingGera Paulos
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in JavaTushar B Kute
 

Tendances (20)

Java Network Programming
Java Network ProgrammingJava Network Programming
Java Network Programming
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Java socket programming
Java socket programmingJava socket programming
Java socket programming
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
Java networking
Java networkingJava networking
Java networking
 
Java Programming - 07 java networking
Java Programming - 07 java networkingJava Programming - 07 java networking
Java Programming - 07 java networking
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Java API: java.net.InetAddress
Java API: java.net.InetAddressJava API: java.net.InetAddress
Java API: java.net.InetAddress
 
Networking & Socket Programming In Java
Networking & Socket Programming In JavaNetworking & Socket Programming In Java
Networking & Socket Programming In Java
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Network programming in Java
Network programming in JavaNetwork programming in Java
Network programming in Java
 
Java sockets
Java socketsJava sockets
Java sockets
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Java Socket Programming
Java Socket ProgrammingJava Socket Programming
Java Socket Programming
 
Basic Networking in Java
Basic Networking in JavaBasic Networking in Java
Basic Networking in Java
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Networking in java, Advanced programming
Networking in java, Advanced programmingNetworking in java, Advanced programming
Networking in java, Advanced programming
 
Chap 1 Network Theory & Java Overview
Chap 1   Network Theory & Java OverviewChap 1   Network Theory & Java Overview
Chap 1 Network Theory & Java Overview
 
Network Programming in Java
Network Programming in JavaNetwork Programming in Java
Network Programming in Java
 

En vedette (20)

Sockets
SocketsSockets
Sockets
 
Socket Programming Tutorial
Socket Programming TutorialSocket Programming Tutorial
Socket Programming Tutorial
 
Ravi Tuppad
Ravi TuppadRavi Tuppad
Ravi Tuppad
 
Java rmi
Java rmiJava rmi
Java rmi
 
Rmi architecture
Rmi architectureRmi architecture
Rmi architecture
 
Basic java
Basic java Basic java
Basic java
 
Introduction To Rmi
Introduction To RmiIntroduction To Rmi
Introduction To Rmi
 
Rmi
RmiRmi
Rmi
 
Java RMI
Java RMIJava RMI
Java RMI
 
remote method invocation
remote method invocationremote method invocation
remote method invocation
 
Networking
NetworkingNetworking
Networking
 
Rmi ppt-2003
Rmi ppt-2003Rmi ppt-2003
Rmi ppt-2003
 
Network Socket Programming with JAVA
Network Socket Programming with JAVANetwork Socket Programming with JAVA
Network Socket Programming with JAVA
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Netty Cookbook - Table of contents
Netty Cookbook - Table of contentsNetty Cookbook - Table of contents
Netty Cookbook - Table of contents
 
Java rmi
Java rmiJava rmi
Java rmi
 
Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)Remote Method Invocation (Java RMI)
Remote Method Invocation (Java RMI)
 
Java Servlets & JSP
Java Servlets & JSPJava Servlets & JSP
Java Servlets & JSP
 
Java servlets
Java servletsJava servlets
Java servlets
 
RMI
RMIRMI
RMI
 

Similaire à Java networking programs - theory

Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project ReportKavita Sharma
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptxEliasPetros
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenVannaSchrader3
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxalfredacavx97
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docxhanneloremccaffery
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxkacie8xcheco
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded wsmile790243
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.comphanleson
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAMaulik Borsaniya
 

Similaire à Java networking programs - theory (20)

Mail Server Project Report
Mail Server Project ReportMail Server Project Report
Mail Server Project Report
 
5_6278455688045789623.pptx
5_6278455688045789623.pptx5_6278455688045789623.pptx
5_6278455688045789623.pptx
 
Socket
SocketSocket
Socket
 
Tcp sockets
Tcp socketsTcp sockets
Tcp sockets
 
Tcpsockets
TcpsocketsTcpsockets
Tcpsockets
 
Client server project
Client server projectClient server project
Client server project
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
 
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
[Type text]ECET465Project 2Project Assignment 2 Building a Mul.docx
 
Java 1
Java 1Java 1
Java 1
 
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docxProject Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
Project Assignment 2 Building a Multi-Threaded Web ServerThis pro.docx
 
692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w692015 programming assignment 1 building a multi­threaded w
692015 programming assignment 1 building a multi­threaded w
 
Md13 networking
Md13 networkingMd13 networking
Md13 networking
 
A.java
A.javaA.java
A.java
 
Socket Programming it-slideshares.blogspot.com
Socket  Programming it-slideshares.blogspot.comSocket  Programming it-slideshares.blogspot.com
Socket Programming it-slideshares.blogspot.com
 
Unit 8 Java
Unit 8 JavaUnit 8 Java
Unit 8 Java
 
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYAPYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
PYTHON -Chapter 5 NETWORK - MAULIK BORSANIYA
 
Multi user chat system using java
Multi user chat system using javaMulti user chat system using java
Multi user chat system using java
 
28 networking
28  networking28  networking
28 networking
 
Lecture10
Lecture10Lecture10
Lecture10
 

Plus de Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

Plus de Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

Dernier

Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 

Dernier (20)

Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Java networking programs - theory

  • 1. Java – Networking Theory Page 1 Java – Networking Theory Socket Basics In client-server applications, the server provides some service, such as processing database queries or sending out web pages. The client uses the service provided by the server, either displaying database query results to the user or displaying the web page in a browser. The communication that occurs between the client and the server must be reliable. That is, no data can be dropped and it must arrive on the client side in the same order in which the server sent it. TCP provides a reliable, point-to-point communication channel that client-server applications on the Internet use to communicate with each other. To communicate over TCP, a client program and a server program establish a connection to one another. Each program binds a socket to its end of the connection. To communicate, the client and the server each reads from and writes to the socket bound to the connection. What Is a Socket? A socket is one end-point of a two-way communication link between two programs running on the network. A socket is a connection between two hosts. It can perform seven basic operations: 1. Connect to a remote machine 2. Send data 3. Receive data 4. Close a connection 5. Bind to a port 6. Listen for incoming data 7. Accept connections from remote machines on the bound port The java.net package provides two classes--Socket and ServerSocket--that implement the client side of the connection and the server side of the connection, respectively. The Socket Class 1. The java.net.Socket class is used for performing client-side TCP operations. Other client- oriented classes that make TCP network connections, such as URL, and URLConnection all ultimately end up invoking the methods of this class. 2. The methods of the Socket class set up and tear down connections and set as various socket options. 3. Because TCP sockets are more or less reliable connections, the interface that the Socket class provides to the programmer is streams. The actual reading and writing of data over the socket is accomplished via stream classes. 4. Java's Socket class, which is used by both clients and servers, has methods that correspond to the first four of the seven operations stated above. [The last three operations are needed only by servers, which wait for clients to connect to them. They are implemented by the ServerSocket class]. 5. Constructors of the Socket class: a) public Socket (String host, int port) This connects a TCP socket to the given host and port. mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 2. 2 Java – Networking Theory Example of use of Socket constructor: try { Socket s = new Socket("www.google.com", 80); // send and receive data... } catch (UnknownHostException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } b) public Socket(InetAddress host, int port) throws IOException This constructor creates a TCP socket to the specified port on the specified host and tries to connect. It differs from the previous constructor in that it uses an InetAddress object to specify the host instead of a hostname. It throws an IOException if it can't connect, but does not throw an UnknownHostException; if the host is unknown, you will find out when you create the InetAddress object. Example: try { InetAddress iadd = InetAddress.getByName("www.google.com"); Socket s = new Socket(iadd, 80); // send and receive data... } catch (UnknownHostException e) { System.err.println(e); } catch (IOException e) { System.err.println(e); } 6. Other methods of Socket class: a) Socket() – creates a socket that has not yet been initialized. b) void connect(SocketAddress add) - connects the socket to the given address c) void connect(SocketAddress add, int timeoutInMillisecs) – connects the socket to the given address or returns if the time interval expired. d) void setTimeout(int timeoutMillisecs) - sets the blocking time for read requests on the socket. When the time out is reached, the InterruptedIOException is raised. e) boolean isConnected() – returns true if the socket is connected f) boolean isClosed() – returns true if the socket is closed. Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 3. Java - Networking Page 3 7. Java programs use client sockets in the following fashion: a) The program creates a new socket with a Socket( ) constructor. b) The socket attempts to connect to the remote host. c) Once the connection is established, the local and remote hosts get input and output streams from the socket and use those streams to send data to each other. This connection is full- duplex; both hosts can send and receive data simultaneously. What the data means depends on the protocol; different commands are sent to an FTP server than to an HTTP server. There will normally be some agreed-upon hand-shaking followed by the transmission of data from one to the other. d) When the transmission of data is complete, one or both sides close the connection. Some protocols, such as HTTP 1.0, require the connection to be closed after each request is serviced. Others, such as FTP, allow multiple requests to be processed in a single connection. The ServerSocket class: 1. The ServerSocket class contains everything you need to write servers in Java. 2. It has constructors that create new ServerSocket objects, methods that listen for connections on a specified port, and methods that return a Socket object when a connection is made so that you can send and receive data. The basic life cycle of a server socket is: 1. A new ServerSocket is created on a particular port using a ServerSocket( ) constructor. 2. The ServerSocket listens for incoming connection on that port using its accept( ) method. When the client connects to the server, accept( ) method returns a Socket object connecting the client and the server. 3. Depending on the type of server, either the Socket's getInputStream() method, getOutputStream( ) method, or both are called to get input and output streams that communicate with the client. 4. The server and the client interact according to an agreed-upon protocol until it is time to close the connection. 5. The server, the client, or both close the connection. 6. The server returns to step 2 and waits for the next connection. If step 4 is likely to take a long or indefinite amount of time, certain servers create a new process to handle each connection so that multiple clients can be serviced at the same time. Java programs should spawn a thread to interact with the client so that the server can be ready to process the next connection sooner. Constructors of the ServerSocket class: 1. public ServerSocket(int port) throws IOException, BindException This constructor creates a server socket on the port specified by the argument. If you don’t pass the port number, the system selects an available port for you. A port chosen for you by the system is sometimes called an anonymous port since you don't know its number. 2. public ServerSocket(int port, int queueLength) throws IOException, BindException This constructor creates a ServerSocket on the specified port with a queue length of your choosing. The queueLength argument sets the length of the queue for incoming connection requests — that is, howmany incoming connections can be stored at one time before the host starts refusing connections. Some operating systems have a maximum queue length, mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 4. 4 Java – Networking Theory typically five. For example, to create a server socket on port 5776 that would hold up to 100 incoming connection requests in the queue, you would write: try { ServerSocket httpd = new ServerSocket(5776, 100); } catch (IOException e) { System.err.println(e); } The constructor throws a BindException if the socket cannot be created and bound to the requested port. An IOException means that the port is already in use. 3. public ServerSocket(int port, int queueLength, InetAddress bindAddress) throws IOException • This constructor creates a ServerSocket on the specified port with the specified queue length. This ServerSocket binds only to the specified local IP address. • This constructor is useful for servers that run on systems with several IP addresses because it allows you to choose the address to which you'll listen. That is, this ServerSocket listens only for incoming connections on the specified address; it won't listen for connections that come in through the host's other addresses. The other constructors bind to all local IP addresses by default. Other methods of the ServerSocket class: Socket accept() – A ServerSocket generally operates in a loop that repeatedly accepts connections. Each pass through the loop invokes the accept() method. This method blocks (stops the flow of execution) the current thread until the connection is made. The method returns a Socket object through which the program can communicate with the client. void close() – Closes the server socket an stop processing any further requests. Internet Addresses: 1. Internet addresses are numerical addresses that consist of 4 bytes in IPv4 (or 16 bytes in IPv6). 2. These addresses are written as a dotted quad like this: 132.163.4.102. Each of these quads can vary from 0 to 255. 3. When your browser requests a web page from another computer on the Internet, it automatically sends your computer’s address where the server should send the web page. This is called your computer’s IP address. 4. It is easier for human beings to deal with host names such as www.google.com instead of the numeric IP addresses. 5. IP address can be static or dynamic. A static IP address is a fixed address and cannot be changed. A dynamic IP address changes every time the user connects to the Internet. 6. The java.net package supports IPv6 addresses provided the host computer’s OS supports these addresses. Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 5. Java - Networking Page 5 7. The java.net package has the InetAddress class to convert between host names and Internet addresses. 8. Methods of InetAddress class: a) public static InetAddress getByName(String host) throws UnknownHostException – this method determines the IP address of a host if the host name is given. b) static InetAddress [] getAllByName(String host) - constructs an array of an Internet addresses for the given host name c) static InetAddress getLocalHost() – constructs an InetAddress for the local host d) byte [] getAddress() – returns an array of bytes that contains numerical address. e) String getHostAddress() – returns a string with decimal numbers separated by periods, e.g., “132.163.4.102” f) String getHostName() – returns the host name The URL 1. URL is the abbreviation of Uniform Resource Locator. 2. It is a reference or an address to a resource on the Internet (e.g., java.sun.com) 3. The URL is the address of a web page; each web page has its own unique address. 4. A URL can be split into 5 parts. Consider the URL http://www.somesite.com/dcn/chap1.html The 5 parts of the URL are as follows: (i) http:// - stands for the protocol. The most common protocol is the HyperText Transfer Protocol. Others are FTP and HTTPS (Secure). (ii) www – This is the sub domain. Some sites use the sub domain ftp, news, etc. (iii) somesite.com – It is the host or domain name. www and the domain name combined together give the IP address. Thus, www.somesite.com can be replaced by an IP address. (iv) dcn – It is a folder or directory and all files are stored in this directory. (v) chap1.html - It is the file which is fetched from the server. If a filename is not specified, the default file is index.html 5. The URL class The URL class has the following constructors: a) URL (String str) - Creates a URL object from the specified string b) URL(URL baseurl, String relativeurl); c) URL(String protocol, String host, int port, String file) – Creates a URL object from the specified protocol, host, port number and file. d) URL(String protocol, String host, String file) – Creates a URL from the specified protocol, hostname and file name. e) The URL object can be constructed like this: URL add = new URL(http://www.dnaindia.com); Such a URL is called an absolute URL. It contains all the information necessary to reach the resource We can also create a relative URL which contains just enough information to reach the resource relative to another URL. mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 6. 6 Java – Networking Theory Example: Consider the base URL http://www.somesite.com/pages Suppose the pages on this site are page1.html and page2.html. We can create URL objects for these pages relative to their common base URL like this: URL add = new URL(“http://www.somesite.com/pages”); URL pg1url = new URL(add, “page1.html”); URL pg2url = new URL(add, “page2.html”); [Ref Program 2 in Java Networking Programs notes] The URLConnection Class 1. The abstract class URLConnection is the superclass of all classes that represent a communications link between the application and a URL. 2. Instances of this class can be used both to read from and to write to the resource referenced by the URL. 3. Creating a connection to a URL requires these steps: i. The connection object is created by invoking the openConnection method on a URL. ii. The setup parameters and general request properties are manipulated. iii. The actual connection to the remote object is made, using the connect method. iv. The remote object becomes available. The header fields and the contents of the remote object can be accessed. 4. The following methods are used to access the header fields and the contents after the connection is made to the remote object: • getContent() - Retrieves the contents of this URL connection. • getHeaderField() - Returns the value of the named header field. • getInputStream() - Returns an input stream that reads from this open connection. • getOutputStream() - Returns an output stream that writes to this connection. 5. Certain header fields are accessed frequently. These are: • getContentEncoding - Returns the value of the content-encoding header field. • getContentLength - Returns the value of the content-length header field. • getContentType - Returns the value of the content-type header field. • getDate - Returns the value of the date header field. • getExpiration - Returns the value of the expires header field. • getLastModifed – Returns the last modified date Serving Multiple Clients 1. A typical server runs on a server computer and clients from all over the Internet might want to use the server at the same time. The server must be able to accept incoming requests from more than one client at a time. This can be done by using threaded programs in Java. 2. Evert time a program has established a new socket connection we will launch a new thread to take care of the connection between the server and that client. 3. The main program will go back and wait for the next connection. 4. Thus, we have to create a loop on the server as follows: Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 7. Java - Networking Page 7 while(true) { Socket incoming = s.accept(); Runnable r = new ThreadedEchoHandler(incoming); Thread t = new Thread(r); t.start(); } The ThreadedEchoHandler class implements the Runnable interface and contains the loop with the client in its run method. class ThreadedEchoHandler implements Runnable { … public void run() { try { Inputstream inps = incoming.getInputStream(); OutputStream outs = incoming.getOutputStream(); //Process input and send response incoming.close(); } catch(Exception ex) { Handle exception } } } Since each connection starts a new thread, multiple clients can connect to the server at the same time. Sending E-Mail 1. A socket program can be used to send email. 2. To send an email, we have to make a socket connection to port 25 which is the SMTP port (SMTP= Simple Mail Transfer Protocol). The SMTP describes the format for email messages. 3. Steps are as follows: i. Open a socket to the host system Socket s = new Socket(“mail.yourserver.com”, 25); // 25 is for SMTP PrintWriter out = new PrintWriter(s.getOutputStream()); [PrintWriter class is used to format representations of objects to a text-output stream. Import the package java.io.Writer for this class.] ii. Send the following information to the print stream: HELO sending host MAIL FROM: <sender e-mail address> mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 8. 8 Java – Networking Theory RCPT TO : <recipient e-mail address> DATA mail message (any number of lines) QUIT The SMTP specification requires that all lines must be terminated with r followed by n. Understanding Ports Generally speaking, a computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection. However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data? Through the use of ports. Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use to deliver the data to the right application. In connection-based communication such as TCP, a server application binds a socket to a specific port number. This has the effect of registering the server with the system to receive all data destined for that port. A client can then rendezvous with the server at the server's port, as illustrated here: Definition: The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer. In datagram-based communication such as UDP, the datagram packet contains the port number of its destination and UDP routes the packet to the appropriate application, as illustrated in this figure: Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services. These ports are called well-known ports. Your applications should not attempt to bind to them. Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 9. Java - Networking Page 9 IMPORTANT QUESTIONS 1. Explain the terms socket and port. 2. How can you get the IP address of a machine from its host name? 3. How can you find out the current IP address of your computer? 4. What is ServerSocket and how is it used? 5. Network server programs are often multithreaded. Explain what this means and why it is true. 6. Using the URL class, write a program to retrieve the file http://www.timesofindia.com/index.html and return the last modified date of this page. 7. Explain the URL class. 8. Explain the URLConnection class 9. Explain the following methods of the URL class: getHost(), getPort(), getProtocol() 10. How can DatagramSocket and DatagramPacket be used to send information across two computers in a network? 11. Write a Java program to accept a URL from the command line. If it uses the HTTP protocol then find the length of its contents. mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani