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



                                 Java – Networking
                                       PROGRAMS
Program 1: Write a program that obtains the IP address of a site.

/* Program to find the IP address of a website */
// Mukesh N Tekwani

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

class AddressDemo
{
     public static void main(String args[]) throws IOException
     {
          BufferedReader br = new BufferedReader(new
                                      InputStreamReader(System.in));

              System.out.print("Enter a website name: ");
              String site = br.readLine();

              try
              {
                     InetAddress ip = InetAddress.getByName(site);
                     System.out.print("The IP address is: " + ip);
              }
              catch(UnknownHostException e)
              {
                   System.out.println("WebSite not found");
              }
       }
}

/* Output:

C:JavaPrgs>java AddressDemo
Enter a website name: www.google.com
The IP address is: www.google.com/74.125.235.50
*/

Modification:
Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the
command line. If the website address is not given at command line, use the default address
http://www.google.com.




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                        Prof. Mukesh N. Tekwani
2                                         Java - Networking


Program 2: Write a program that connects to the home page of www.yahoo.com (read
from a URL).

//Program to connect to the home page of www.yahoo.com
// Mukesh N Tekwani

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

public class URLReader
{
     public static void main(String[] args) throws Exception
     {
          URL myurl = new URL("http://www.yahoo.com/");
          BufferedReader in = new BufferedReader(new
                             InputStreamReader(myurl.openStream()));
          String inputLine;

              while ((inputLine = in.readLine()) != null)
                   System.out.println(inputLine);
              in.close();
       }
}

Output:
When this program is run, it displays the complete HTML code of the web page.

Possible Error: If we give site address simply as www.yahoo.com, we get MalformedURLException.
The protocol http must also be given in the complete URL.

Modification:
Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the
command line. If the website address is not given at command line, use the default address
http://www.google.com.




Prof. Mukesh N Tekwani                     mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                        Page 3


Program 3: Write a program that parses a URL address into its components.

//Program to parse a URL address into its components
// Mukesh N Tekwani

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

public class ParseAddress
{
     public static void main (String[] args)
     {
          if (args.length !=1)
          {
                System.out.println ("Error: missing url argument");
                System.out.println ("Usage: java ParseURL <url>");
                System.exit (0);
          }
          try
          {
                URL siteurl = new URL (args[0]);
                System.out.println ("Protocol = " +
                                     siteurl.getProtocol ());
                System.out.println("Host = " + siteurl.getHost ());
                System.out.println("File name= " + siteurl.getFile());
                System.out.println("Port = " + siteurl.getPort ());
                System.out.println("Target = " + siteurl.getRef ());
          }
          catch (MalformedURLException e)
          {
                System.out.println ("Bad URL = " + args[0]);
          }
     } // main
} // class ParseAddress

Output:
C:JavaPrgs>java ParseAddress http://www.microsoft.com
Protocol = http
Host = www.microsoft.com
File name =
Port = -1
Target = null




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                 Prof. Mukesh N. Tekwani
4                                   Java - Networking


Program 4: Write a program to translate an IP address into host name or a host name to
an IP address.
// Translate IP address to hostname or vice-versa
// Mukesh N Tekwani
import java.net.*;
import java.io.*;

class TranslateAddress
{
     public static void main (String args[])
     {
          if (args.length != 1)
          {
                System.out.println ("Error! No IP or host name
                                     address");
                System.out.println ("Usage: java TranslateAddress
                                     java.sun.com");
                System.out.println ("    or java TranslateAddress
                                     209.249.116.143");
                System.exit (0);
          }
          try
          {
                // When the argument passed is a host name(e.g.
                // sun.com), the corresponding IP address is returned.
                // If passed an IP address, then only the IP address
                // is returned.

                    InetAddress ipadd = InetAddress.getByName (args[0]);
                    System.out.println ("Address " + args[0] + " = " +
                                    ipadd);

                    // To get the hostname when passed an IP address use
                    // getHostName (), which will return the host name
                    // string.
                    System.out.println ("Name of " + args[0] + " = " +
                                    ipadd.getHostName ());
            }
            catch    (UnknownHostException e)
            {
                    System.out.println ("Unable to translate the
                                         address.");
           }
      } // main
   } // class TranslateAddress
/* Output:
C:JavaPrgs>java TranslateAddress 130.237.34.133
Address 130.237.34.133 = /130.237.34.133
Name of 130.237.34.133 = ns1.particle.kth.se
*/




Prof. Mukesh N Tekwani               mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                               Page 5


Program 5: Write a program to print all the addresses of www.microsoft.com

// Get all IP addresses by name of site
// Mukesh N Tekwani

import java.net.*;

public class AllAddressesOfMicrosoft
{
       public static void main (String[] args)
     {
           try
           {
                InetAddress[] ipadd =
                      InetAddress.getAllByName("www.microsoft.com");
                for (int i = 0; i < ipadd.length; i++)
                {
                      System.out.println(ipadd[i]);
                }
           }
           catch (UnknownHostException ex)
           {
               System.out.println("Could not find www.microsoft.com");
           }
     }
}

/*Output:

C:JavaPrgs>java AllAddressesOfMicrosoft

www.microsoft.com/64.4.31.252
www.microsoft.com/65.55.12.249
www.microsoft.com/65.55.21.250
www.microsoft.com/207.46.131.43
www.microsoft.com/207.46.170.10
www.microsoft.com/207.46.170.123
*/

Modification: Write a program that prints the Internet Address of the local host if we do not
specify any command-line parameters or all Internet addresses of another host if we specify the host
name on the command line.




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                           Prof. Mukesh N. Tekwani
6                                    Java - Networking


Program 6: Write a program to obtain the IP address of the local machine.

// Find the IP address of the local machine
// Mukesh n Tekwani

import java.net.*;
public class MyOwnAddress
{
       public static void main (String[] args)
     {
           try
           {
                InetAddress me = InetAddress.getLocalHost();
                String myadd = me.getHostAddress();
                System.out.println("My address is " + myadd);
           }
           catch (UnknownHostException e)
           {
                System.out.println("I'm sorry. I don't know my own
                           address; really lost!!!.");
           }
     }
}

/* Output:
C:JavaPrgs>java MyOwnAddress
My address is 192.168.1.7
*/




Prof. Mukesh N Tekwani                mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                          Page 7


Program 7: Write a program that accepts an IP address and finds the host name.

// Given the IP address, find the host name
// Mukesh N Tekwani

import java.net.*;
public class ReverseTest
{
     public static void main (String[] args)
     {
          try
          {
                InetAddress ia =
                     InetAddress.getByName("65.55.21.250");

                   System.out.println(ia.getHostName());
                   System.out.println(ia);
             }
             catch (Exception e)
             {
                  System.out.println(e);
             }
      }
}

/* Output:
C:JavaPrgs>java ReverseTest
wwwco1vip.microsoft.com
wwwco1vip.microsoft.com/65.55.21.250
*/




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                  Prof. Mukesh N. Tekwani
8                                   Java - Networking


Program 8: Write a program to download a file from the Internet and either copy it as a
file on the local machine or display it on the screen.
// Program-download a file & copy it as a file or display it on screen
// Mukesh N Tekwani
import java.io.*;
import java.net.*;
public class DownLoadFile
{
     public static void main(String args[])
     {
          InputStream in = null;
          OutputStream out = null;
            try
            {
                   if ((args.length != 1) && (args.length != 2))
                        throw new IllegalArgumentException("Wrong no. of
                             arguments");

                   URL siteurl = new URL(args[0]);
                   in = siteurl.openStream();
                   if(args.length == 2)
                        out = new FileOutputStream(args[1]);
                   else
                        out = System.out; //display on client machine
                   byte [] buffer = new byte[4096];
                   int bytes_read;
                   while((bytes_read = in.read(buffer)) != -1)
                   out.write(buffer, 0, bytes_read);
            }
            catch (Exception ex)
            {
                 System.out.println(ex);
            }
            finally
            {
                 try
                 {
                      in.close(); out.close();
                 }
                 catch (Exception ae)
                 {
                      System.out.println(ae);
                 }
            }
     }
}
/* Output:
C:JavaPrgs>java DownLoadFile http://www.yahoo.com test.txt
*/


Prof. Mukesh N Tekwani               mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                           Page 9


                       CLIENT-SERVER PROGRAMS (Using Sockets)

              Client                                           Server
 Create TCP Socket                             Create TCP Socket
 Socket       cs     = new                     ServerSocket        ss           =        new
 Socket(hostname, port);                       ServerSocket(port);

 Client initiates the communication            Wait for client connection
 by reading the user input                     Socket        listen_socket                 =
 Str                              =            ss.accept();
 userinput.readLine();                         Then reads the client on listen_socket.

 Then sends it to server                       Server listens client
 Server_out.writeBytes(str                     client_str                                  =
 + ‘n’);                                      client_input.readLine();

 Client listens to server using client         Server sends reply to client
 socket


 Close client socket




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                     Prof. Mukesh N. Tekwani
10                                   Java - Networking


 Program 9: Write a client/server program in which a client sends a single string to the
 server. The server just displays this string. (Echo)

 Server Program:
 //Server Program
 //Works with file Client1
 //Mukesh N Tekwani

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

 class Server1
 {
      public static void main(String args[]) throws Exception
      {
            //create server socket
            ServerSocket ss = new ServerSocket(4444);

             while (true)
             {
                  Socket listen_socket = ss.accept();
                  BufferedReader client_input = new BufferedReader(new
                        InputStreamReader(listen_socket.getInputStream()));

                    String client_str;      //to store string rcvd from client

                    client_str = client_input.readLine();
                    System.out.println(client_str);
             }
       }
 }

 Client Program:
 //Client Program
 //Works with file Server1
 //Mukesh N Tekwani

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

 class Client1
 {
      public static void main(String args[]) throws Exception
      {
            //create client socket
            Socket cs = new Socket("localhost", 4444);

             BufferedReader user_input = new BufferedReader(new
                        InputStreamReader(System.in));

             DataOutputStream server_out = new
                        DataOutputStream(cs.getOutputStream());



 Prof. Mukesh N Tekwani               mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                         Page 11


             String str;

             str = user_input.readLine();

             server_out.writeBytes(str + 'n');

             cs.close();
      }
}

Program : Write a TCP/IP client / server program that sends a string in lowercase to the
server which sends the equivalent uppercase string back to the client.

Server Program:
//The server code Server.java:

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

public class ServerLower
{

      // the socket used by the server
      private ServerSocket serverSocket;
      ServerLower(int port)            // server constructor
      {
           /* create socket server and wait for connection requests */
           try
           {
                 serverSocket = new ServerSocket(port);
                 System.out.println("Server waiting for client on port " +
                            serverSocket.getLocalPort());

                   while(true)
                   {
                        Socket socket = serverSocket.accept();
                        System.out.println("New client asked for a
                              connection");
                        TcpThread t = new TcpThread(socket);
                        System.out.println("Starting a thread for a new
                              Client");
                        t.start();
                   }
             }
             catch (IOException e)
             {
                  System.out.println("Exception on new ServerSocket:" + e);
             }
      }

      public static void main(String[] arg)
      {
           new ServerLower(4444);
      }

mukeshtekwani@hotmail.com [Mobile:9869 488 356]                  Prof. Mukesh N. Tekwani
12                                 Java - Networking



       /** One instance of this thread will run for each client */
       class TcpThread extends Thread
       {
            Socket socket;        // the socket where to listen/talk
            ObjectInputStream Sinput;
            ObjectOutputStream Soutput;

             TcpThread(Socket socket)
             {
                  this.socket = socket;
             }

             public void run()
             {
                  /* Creating both Data Streams */
                  System.out.println("Thread trying to create Object
                                   Input/Output Streams");
                  try
                  {
                        // create output first
                        Soutput = new
                             ObjectOutputStream(socket.getOutputStream());
                        Soutput.flush();
                        Sinput = new
                             ObjectInputStream(socket.getInputStream());
                  }
                  catch (IOException e)
                  {
                        System.out.println("Exception creating new
                                   Input/output Streams: " + e);
                        return;
                  }
                  System.out.println("Thread waiting for a String from the
                             Client");
                  // read a String (which is an object)
                  try
                  {
                        String str = (String) Sinput.readObject();

                          str = str.toUpperCase(); //convert lower 2 uppercase

                          Soutput.writeObject(str);
                          Soutput.flush();
                   }
                   catch (IOException e)
                   {
                        System.out.println("Exception reading/writing
                              Streams: " + e);
                        return;
                   }
                   catch (ClassNotFoundException e1)
                   {    //nothing needed here
                   }
                   finally

 Prof. Mukesh N Tekwani             mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                  Page 13


                   {
                         try
                         {
                                Soutput.close();
                                Sinput.close();
                         }
                         catch (Exception e2)
                         {    //nothing needed here

                         }
                   }
            }
      }
}


Client Program:
//The client code that sends a string in lowercase to the server

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

public class ClientLower
{
     ObjectInputStream Sinput; // to read the socker
     ObjectOutputStream Soutput; // towrite on the socket
     Socket socket;

      // Constructor connection receiving a socket number
      ClientLower(int port)
      {
           try
           {
                 socket = new Socket("localhost", port);
           }
           catch(Exception e)
           {
                 System.out.println("Error connectiong to server:" + e);
                 return;
           }
           System.out.println("Connection accepted " +
                 socket.getInetAddress() + ":" + socket.getPort());

            /* Creating both Data Streams */
            try
            {
                 Sinput = new ObjectInputStream(socket.getInputStream());
                 Soutput = new
                       ObjectOutputStream(socket.getOutputStream());
            }
            catch (IOException e)
            {
                 System.out.println("Exception creating I/O Streams:"+ e);
                 return;
            }

mukeshtekwani@hotmail.com [Mobile:9869 488 356]           Prof. Mukesh N. Tekwani
14                                           Java - Networking



                String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ";

                // send the string to the server
                System.out.println("Client sending "" + test + "" to
                     server");
                try
                {
                     Soutput.writeObject(test);
                     Soutput.flush();
                }
                catch(IOException e)
                {
                     System.out.println("Error writting to the socket: " + e);
                     return;
                }
                // read back the answer from the server
                String response;
                try
                {
                     response = (String) Sinput.readObject();
                     System.out.println("Read back from server: " + response);
                }
                catch(Exception e)
                {
                     System.out.println("Problem reading back from server: " + e);
                }

                try
                {
                        Sinput.close();
                        Soutput.close();
                }
                catch(Exception e)
                {    // nothing needed here
                }
        }

        public static void main(String[] arg)
        {
             new ClientLower(4444);
        }
 }

 Modifications:
 1. Modify the Server program in this example so that it is not multithreaded.
 2. Modify the client program so that the input string is entered by the user from keyboard when program
    runs, instead of storing it within the program.




 Prof. Mukesh N Tekwani                        mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                       Page 15


Program 17:
Write a client-server socket application in which
(i)   A client reads a character from the keyboard and sends the character out of its
      socket to the server.
(ii)  The server reads the character from its connection socket
(iii) The server finds the ASCII value of the character.
(iv) The server sends the ASCII value out of its connection socket to the client.
(v)   The client reads the result from its socket and prints the result on its standard
      output device.

Server Program:
//Server sends the ASCII code of a character to client
//Mukesh N Tekwani
import java.io.*;
import java.net.*;
class ServerASCII
{
     public static void main(String args[]) throws Exception
     {
           String clientstr, serverstr;

              ServerSocket ss = new ServerSocket(4444);

              while(true)
              {
                   Socket cs = ss.accept();
                   System.out.println("Connected to client...");

                        BufferedReader inFromClient = new BufferedReader(new
                                   InputStreamReader(cs.getInputStream()));

                        DataOutputStream outToClient = new
                                   DataOutputStream(cs.getOutputStream());

                        clientstr = inFromClient.readLine();

                        //read the first character from input
                        char c = clientstr.charAt(0);

                        /* Find the ASCII code; note the type casting */
                        serverstr = "The ASCII code of " + clientstr + " is        " +
                                   (int)c + 'n';

                        outToClient.writeBytes(serverstr);
              }
       }
}
Output at Client end:
C:JavaPrgs>java ClientASCII
Enter a character
B
From server: The ASCII code of B is          66

mukeshtekwani@hotmail.com [Mobile:9869 488 356]                 Prof. Mukesh N. Tekwani
16                                              Java - Networking


                                         PORTS AND SOCKETS

 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.


 Understanding Sockets

 In client-server applications, the server provides some service, such as processing database queries or sending
 out current stock prices. The client uses the service provided by the server, either displaying database query
 results to the user or making stock purchase recommendations to an investor. 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.

 Prof. Mukesh N Tekwani                          mukeshtekwani@hotmail.com [Mobile:9869 488 356]
Java - Networking                                   Page 17


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.
Socket classes are used to represent the connection between a client program and a server program. 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.




mukeshtekwani@hotmail.com [Mobile:9869 488 356]                                 Prof. Mukesh N. Tekwani

Contenu connexe

Tendances

Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programmingashok hirpara
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)UC San Diego
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sksureshkarthick37
 
Java- Datagram Socket class & Datagram Packet class
Java- Datagram Socket class  & Datagram Packet classJava- Datagram Socket class  & Datagram Packet class
Java- Datagram Socket class & Datagram Packet classRuchi Maurya
 
A Short Java Socket Tutorial
A Short Java Socket TutorialA Short Java Socket Tutorial
A Short Java Socket TutorialGuo Albert
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagarNitish Nagar
 
Multiplayer Java Game
Multiplayer Java GameMultiplayer Java Game
Multiplayer Java Gamekarim baidar
 

Tendances (20)

Networking in java
Networking in javaNetworking in java
Networking in java
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Advance Java-Network Programming
Advance Java-Network ProgrammingAdvance Java-Network Programming
Advance Java-Network Programming
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Socket programming in Java (PPTX)
Socket programming in Java (PPTX)Socket programming in Java (PPTX)
Socket programming in Java (PPTX)
 
Socket programming-tutorial-sk
Socket programming-tutorial-skSocket programming-tutorial-sk
Socket programming-tutorial-sk
 
Java sockets
Java socketsJava sockets
Java sockets
 
Java- Datagram Socket class & Datagram Packet class
Java- Datagram Socket class  & Datagram Packet classJava- Datagram Socket class  & Datagram Packet class
Java- Datagram Socket class & Datagram Packet class
 
Tcp/ip server sockets
Tcp/ip server socketsTcp/ip server sockets
Tcp/ip server sockets
 
Java Programming - 07 java networking
Java Programming - 07 java networkingJava Programming - 07 java networking
Java Programming - 07 java networking
 
A Short Java Socket Tutorial
A Short Java Socket TutorialA Short Java Socket Tutorial
A Short Java Socket Tutorial
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
 
Socket Programming - nitish nagar
Socket Programming - nitish nagarSocket Programming - nitish nagar
Socket Programming - nitish nagar
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
A.java
A.javaA.java
A.java
 
Ppt of socket
Ppt of socketPpt of socket
Ppt of socket
 
Multiplayer Java Game
Multiplayer Java GameMultiplayer Java Game
Multiplayer Java Game
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Sockets
SocketsSockets
Sockets
 

Similaire à Java networking programs socket based

Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13Sasi Kala
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqelajobandesther
 
Csmr2012 bettenburg presentation
Csmr2012 bettenburg presentationCsmr2012 bettenburg presentation
Csmr2012 bettenburg presentationSAIL_QU
 
nw-lab_dns-server.pdf
nw-lab_dns-server.pdfnw-lab_dns-server.pdf
nw-lab_dns-server.pdfJayaprasanna4
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideSharebiyu
 
Baocao Web Tech Java Mail
Baocao Web Tech Java MailBaocao Web Tech Java Mail
Baocao Web Tech Java Mailxicot
 
network programing lab file ,
network programing lab file ,network programing lab file ,
network programing lab file ,AAlha PaiKra
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxDhrumilSheth3
 

Similaire à Java networking programs socket based (20)

JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
Lab manual cn-2012-13
Lab manual cn-2012-13Lab manual cn-2012-13
Lab manual cn-2012-13
 
Lecture6
Lecture6Lecture6
Lecture6
 
Testing in android
Testing in androidTesting in android
Testing in android
 
My java file
My java fileMy java file
My java file
 
Run rmi
Run rmiRun rmi
Run rmi
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
Csmr2012 bettenburg presentation
Csmr2012 bettenburg presentationCsmr2012 bettenburg presentation
Csmr2012 bettenburg presentation
 
Network programming1
Network programming1Network programming1
Network programming1
 
nw-lab_dns-server.pdf
nw-lab_dns-server.pdfnw-lab_dns-server.pdf
nw-lab_dns-server.pdf
 
香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare香港六合彩 &raquo; SlideShare
香港六合彩 &raquo; SlideShare
 
Baocao Web Tech Java Mail
Baocao Web Tech Java MailBaocao Web Tech Java Mail
Baocao Web Tech Java Mail
 
network programing lab file ,
network programing lab file ,network programing lab file ,
network programing lab file ,
 
Java practical
Java practicalJava practical
Java practical
 
Java networking
Java networkingJava networking
Java networking
 
java sockets
 java sockets java sockets
java sockets
 
CHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptxCHAPTER - 3 - JAVA NETWORKING.pptx
CHAPTER - 3 - JAVA NETWORKING.pptx
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
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

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structuredhanjurrannsibayan2
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsKarakKing
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...Poonam Aher Patil
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.MaryamAhmad92
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxUmeshTimilsina1
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...pradhanghanshyam7136
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfSherif Taha
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 

Dernier (20)

Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

Java networking programs socket based

  • 1. Java – Networking Page 1 Java – Networking PROGRAMS Program 1: Write a program that obtains the IP address of a site. /* Program to find the IP address of a website */ // Mukesh N Tekwani import java.io.*; import java.net.*; class AddressDemo { public static void main(String args[]) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Enter a website name: "); String site = br.readLine(); try { InetAddress ip = InetAddress.getByName(site); System.out.print("The IP address is: " + ip); } catch(UnknownHostException e) { System.out.println("WebSite not found"); } } } /* Output: C:JavaPrgs>java AddressDemo Enter a website name: www.google.com The IP address is: www.google.com/74.125.235.50 */ Modification: Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the command line. If the website address is not given at command line, use the default address http://www.google.com. mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 2. 2 Java - Networking Program 2: Write a program that connects to the home page of www.yahoo.com (read from a URL). //Program to connect to the home page of www.yahoo.com // Mukesh N Tekwani import java.net.*; import java.io.*; public class URLReader { public static void main(String[] args) throws Exception { URL myurl = new URL("http://www.yahoo.com/"); BufferedReader in = new BufferedReader(new InputStreamReader(myurl.openStream())); String inputLine; while ((inputLine = in.readLine()) != null) System.out.println(inputLine); in.close(); } } Output: When this program is run, it displays the complete HTML code of the web page. Possible Error: If we give site address simply as www.yahoo.com, we get MalformedURLException. The protocol http must also be given in the complete URL. Modification: Modify the above program so that it takes the website name (e.g., http://www.yahoo.com) from the command line. If the website address is not given at command line, use the default address http://www.google.com. Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
  • 3. Java - Networking Page 3 Program 3: Write a program that parses a URL address into its components. //Program to parse a URL address into its components // Mukesh N Tekwani import java.net.*; import java.io.*; public class ParseAddress { public static void main (String[] args) { if (args.length !=1) { System.out.println ("Error: missing url argument"); System.out.println ("Usage: java ParseURL <url>"); System.exit (0); } try { URL siteurl = new URL (args[0]); System.out.println ("Protocol = " + siteurl.getProtocol ()); System.out.println("Host = " + siteurl.getHost ()); System.out.println("File name= " + siteurl.getFile()); System.out.println("Port = " + siteurl.getPort ()); System.out.println("Target = " + siteurl.getRef ()); } catch (MalformedURLException e) { System.out.println ("Bad URL = " + args[0]); } } // main } // class ParseAddress Output: C:JavaPrgs>java ParseAddress http://www.microsoft.com Protocol = http Host = www.microsoft.com File name = Port = -1 Target = null mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 4. 4 Java - Networking Program 4: Write a program to translate an IP address into host name or a host name to an IP address. // Translate IP address to hostname or vice-versa // Mukesh N Tekwani import java.net.*; import java.io.*; class TranslateAddress { public static void main (String args[]) { if (args.length != 1) { System.out.println ("Error! No IP or host name address"); System.out.println ("Usage: java TranslateAddress java.sun.com"); System.out.println (" or java TranslateAddress 209.249.116.143"); System.exit (0); } try { // When the argument passed is a host name(e.g. // sun.com), the corresponding IP address is returned. // If passed an IP address, then only the IP address // is returned. InetAddress ipadd = InetAddress.getByName (args[0]); System.out.println ("Address " + args[0] + " = " + ipadd); // To get the hostname when passed an IP address use // getHostName (), which will return the host name // string. System.out.println ("Name of " + args[0] + " = " + ipadd.getHostName ()); } catch (UnknownHostException e) { System.out.println ("Unable to translate the address."); } } // main } // class TranslateAddress /* Output: C:JavaPrgs>java TranslateAddress 130.237.34.133 Address 130.237.34.133 = /130.237.34.133 Name of 130.237.34.133 = ns1.particle.kth.se */ Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
  • 5. Java - Networking Page 5 Program 5: Write a program to print all the addresses of www.microsoft.com // Get all IP addresses by name of site // Mukesh N Tekwani import java.net.*; public class AllAddressesOfMicrosoft { public static void main (String[] args) { try { InetAddress[] ipadd = InetAddress.getAllByName("www.microsoft.com"); for (int i = 0; i < ipadd.length; i++) { System.out.println(ipadd[i]); } } catch (UnknownHostException ex) { System.out.println("Could not find www.microsoft.com"); } } } /*Output: C:JavaPrgs>java AllAddressesOfMicrosoft www.microsoft.com/64.4.31.252 www.microsoft.com/65.55.12.249 www.microsoft.com/65.55.21.250 www.microsoft.com/207.46.131.43 www.microsoft.com/207.46.170.10 www.microsoft.com/207.46.170.123 */ Modification: Write a program that prints the Internet Address of the local host if we do not specify any command-line parameters or all Internet addresses of another host if we specify the host name on the command line. mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 6. 6 Java - Networking Program 6: Write a program to obtain the IP address of the local machine. // Find the IP address of the local machine // Mukesh n Tekwani import java.net.*; public class MyOwnAddress { public static void main (String[] args) { try { InetAddress me = InetAddress.getLocalHost(); String myadd = me.getHostAddress(); System.out.println("My address is " + myadd); } catch (UnknownHostException e) { System.out.println("I'm sorry. I don't know my own address; really lost!!!."); } } } /* Output: C:JavaPrgs>java MyOwnAddress My address is 192.168.1.7 */ Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
  • 7. Java - Networking Page 7 Program 7: Write a program that accepts an IP address and finds the host name. // Given the IP address, find the host name // Mukesh N Tekwani import java.net.*; public class ReverseTest { public static void main (String[] args) { try { InetAddress ia = InetAddress.getByName("65.55.21.250"); System.out.println(ia.getHostName()); System.out.println(ia); } catch (Exception e) { System.out.println(e); } } } /* Output: C:JavaPrgs>java ReverseTest wwwco1vip.microsoft.com wwwco1vip.microsoft.com/65.55.21.250 */ mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 8. 8 Java - Networking Program 8: Write a program to download a file from the Internet and either copy it as a file on the local machine or display it on the screen. // Program-download a file & copy it as a file or display it on screen // Mukesh N Tekwani import java.io.*; import java.net.*; public class DownLoadFile { public static void main(String args[]) { InputStream in = null; OutputStream out = null; try { if ((args.length != 1) && (args.length != 2)) throw new IllegalArgumentException("Wrong no. of arguments"); URL siteurl = new URL(args[0]); in = siteurl.openStream(); if(args.length == 2) out = new FileOutputStream(args[1]); else out = System.out; //display on client machine byte [] buffer = new byte[4096]; int bytes_read; while((bytes_read = in.read(buffer)) != -1) out.write(buffer, 0, bytes_read); } catch (Exception ex) { System.out.println(ex); } finally { try { in.close(); out.close(); } catch (Exception ae) { System.out.println(ae); } } } } /* Output: C:JavaPrgs>java DownLoadFile http://www.yahoo.com test.txt */ Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
  • 9. Java - Networking Page 9 CLIENT-SERVER PROGRAMS (Using Sockets) Client Server Create TCP Socket Create TCP Socket Socket cs = new ServerSocket ss = new Socket(hostname, port); ServerSocket(port); Client initiates the communication Wait for client connection by reading the user input Socket listen_socket = Str = ss.accept(); userinput.readLine(); Then reads the client on listen_socket. Then sends it to server Server listens client Server_out.writeBytes(str client_str = + ‘n’); client_input.readLine(); Client listens to server using client Server sends reply to client socket Close client socket mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 10. 10 Java - Networking Program 9: Write a client/server program in which a client sends a single string to the server. The server just displays this string. (Echo) Server Program: //Server Program //Works with file Client1 //Mukesh N Tekwani import java.io.*; import java.net.*; class Server1 { public static void main(String args[]) throws Exception { //create server socket ServerSocket ss = new ServerSocket(4444); while (true) { Socket listen_socket = ss.accept(); BufferedReader client_input = new BufferedReader(new InputStreamReader(listen_socket.getInputStream())); String client_str; //to store string rcvd from client client_str = client_input.readLine(); System.out.println(client_str); } } } Client Program: //Client Program //Works with file Server1 //Mukesh N Tekwani import java.io.*; import java.net.*; class Client1 { public static void main(String args[]) throws Exception { //create client socket Socket cs = new Socket("localhost", 4444); BufferedReader user_input = new BufferedReader(new InputStreamReader(System.in)); DataOutputStream server_out = new DataOutputStream(cs.getOutputStream()); Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
  • 11. Java - Networking Page 11 String str; str = user_input.readLine(); server_out.writeBytes(str + 'n'); cs.close(); } } Program : Write a TCP/IP client / server program that sends a string in lowercase to the server which sends the equivalent uppercase string back to the client. Server Program: //The server code Server.java: import java.io.*; import java.net.*; public class ServerLower { // the socket used by the server private ServerSocket serverSocket; ServerLower(int port) // server constructor { /* create socket server and wait for connection requests */ try { serverSocket = new ServerSocket(port); System.out.println("Server waiting for client on port " + serverSocket.getLocalPort()); while(true) { Socket socket = serverSocket.accept(); System.out.println("New client asked for a connection"); TcpThread t = new TcpThread(socket); System.out.println("Starting a thread for a new Client"); t.start(); } } catch (IOException e) { System.out.println("Exception on new ServerSocket:" + e); } } public static void main(String[] arg) { new ServerLower(4444); } mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 12. 12 Java - Networking /** One instance of this thread will run for each client */ class TcpThread extends Thread { Socket socket; // the socket where to listen/talk ObjectInputStream Sinput; ObjectOutputStream Soutput; TcpThread(Socket socket) { this.socket = socket; } public void run() { /* Creating both Data Streams */ System.out.println("Thread trying to create Object Input/Output Streams"); try { // create output first Soutput = new ObjectOutputStream(socket.getOutputStream()); Soutput.flush(); Sinput = new ObjectInputStream(socket.getInputStream()); } catch (IOException e) { System.out.println("Exception creating new Input/output Streams: " + e); return; } System.out.println("Thread waiting for a String from the Client"); // read a String (which is an object) try { String str = (String) Sinput.readObject(); str = str.toUpperCase(); //convert lower 2 uppercase Soutput.writeObject(str); Soutput.flush(); } catch (IOException e) { System.out.println("Exception reading/writing Streams: " + e); return; } catch (ClassNotFoundException e1) { //nothing needed here } finally Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
  • 13. Java - Networking Page 13 { try { Soutput.close(); Sinput.close(); } catch (Exception e2) { //nothing needed here } } } } } Client Program: //The client code that sends a string in lowercase to the server import java.net.*; import java.io.*; public class ClientLower { ObjectInputStream Sinput; // to read the socker ObjectOutputStream Soutput; // towrite on the socket Socket socket; // Constructor connection receiving a socket number ClientLower(int port) { try { socket = new Socket("localhost", port); } catch(Exception e) { System.out.println("Error connectiong to server:" + e); return; } System.out.println("Connection accepted " + socket.getInetAddress() + ":" + socket.getPort()); /* Creating both Data Streams */ try { Sinput = new ObjectInputStream(socket.getInputStream()); Soutput = new ObjectOutputStream(socket.getOutputStream()); } catch (IOException e) { System.out.println("Exception creating I/O Streams:"+ e); return; } mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 14. 14 Java - Networking String test = "aBcDeFgHiJkLmNoPqRsTuVwXyZ"; // send the string to the server System.out.println("Client sending "" + test + "" to server"); try { Soutput.writeObject(test); Soutput.flush(); } catch(IOException e) { System.out.println("Error writting to the socket: " + e); return; } // read back the answer from the server String response; try { response = (String) Sinput.readObject(); System.out.println("Read back from server: " + response); } catch(Exception e) { System.out.println("Problem reading back from server: " + e); } try { Sinput.close(); Soutput.close(); } catch(Exception e) { // nothing needed here } } public static void main(String[] arg) { new ClientLower(4444); } } Modifications: 1. Modify the Server program in this example so that it is not multithreaded. 2. Modify the client program so that the input string is entered by the user from keyboard when program runs, instead of storing it within the program. Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
  • 15. Java - Networking Page 15 Program 17: Write a client-server socket application in which (i) A client reads a character from the keyboard and sends the character out of its socket to the server. (ii) The server reads the character from its connection socket (iii) The server finds the ASCII value of the character. (iv) The server sends the ASCII value out of its connection socket to the client. (v) The client reads the result from its socket and prints the result on its standard output device. Server Program: //Server sends the ASCII code of a character to client //Mukesh N Tekwani import java.io.*; import java.net.*; class ServerASCII { public static void main(String args[]) throws Exception { String clientstr, serverstr; ServerSocket ss = new ServerSocket(4444); while(true) { Socket cs = ss.accept(); System.out.println("Connected to client..."); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(cs.getInputStream())); DataOutputStream outToClient = new DataOutputStream(cs.getOutputStream()); clientstr = inFromClient.readLine(); //read the first character from input char c = clientstr.charAt(0); /* Find the ASCII code; note the type casting */ serverstr = "The ASCII code of " + clientstr + " is " + (int)c + 'n'; outToClient.writeBytes(serverstr); } } } Output at Client end: C:JavaPrgs>java ClientASCII Enter a character B From server: The ASCII code of B is 66 mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani
  • 16. 16 Java - Networking PORTS AND SOCKETS 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. Understanding Sockets In client-server applications, the server provides some service, such as processing database queries or sending out current stock prices. The client uses the service provided by the server, either displaying database query results to the user or making stock purchase recommendations to an investor. 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. Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com [Mobile:9869 488 356]
  • 17. Java - Networking Page 17 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. Socket classes are used to represent the connection between a client program and a server program. 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. mukeshtekwani@hotmail.com [Mobile:9869 488 356] Prof. Mukesh N. Tekwani