Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses
Showing posts with label Networking in Java. Show all posts
Showing posts with label Networking in Java. Show all posts

How to read source of a Url using java.net API ?.

Program to demonstrate how to read page source of a Url using java.net API.

package com.hubberspot.code;

import java.net.MalformedURLException;
import java.net.URL;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadUrlDemo {

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

   // Create a URL object by providing URL in the form of String.
   URL url = new URL("http://www.hubberspot.com");

   try {

    // Creating a BufferedReader object for reading the
    // contents of URL by passing an object of InputStreamReader.
    // URL object created above has a method called as openStream()
    // This method opens a connection to the url passed and returns 
    // an InputStream for reading from that connection.
    BufferedReader in = new BufferedReader(
      new InputStreamReader(
        url.openStream()));

    // Creating a String object to store the contents of url line 
    // by line
    String output;

    // BufferedReader has a method called as readLine() reads a 
    // line of text. A line is terminated by line feed ('\n') 
    // a carriage return ('\r'). It returns a null is nothing is read 
    // Applying a while based on the condition till the readline method
    // returns something.
    // Finally printing on the console.
    while ((output = in.readLine()) != null) {
     System.out.println(output);
    }

    // Closing BufferedReader by close method ... very important for
    // resource management
    in.close();
   } catch (IOException ex) {
    ex.printStackTrace();
   }
  } catch (MalformedURLException ex) {
   ex.printStackTrace();
  }
 }
}



Output of the program : 


 

How to parse a given URL to get information about it in Java ?.


Program to in demonstrate how to parse a given URL to get information about it in Java

package com.hubberspot.code;

import java.io.IOException;
import java.net.URL;

public class ParsingUrlDemo {

 public static void main(String[] args) {

  URL url = null;

  try {

   // Create a URL object by providing URL in the form of String.
   url = new URL("http://www.hubberspot.com/search/label/EJB?Java=ejb");

   // getHost() : Returns the host name of this URL.
   String host = url.getHost();

   // getPath() : Gets the path of this URL.
   String path = url.getPath();

   // getQuery() : Gets the searched query in the URL.
   String query = url.getQuery();

   // getProtocol() : Gets the protocol used to refer this URL. 
   String protocol = url.getProtocol();

   // getAuthority() : Gets the authority of the URL.
   String authority = url.getAuthority();

   // getRef() : Gets the anchor of this URL. 
   String reference = url.getRef();

   System.out.println("URL: " + url.toString() + 
     " \nparses to the following:\n");
   System.out.println("Host of the Url : " + host);
   System.out.println("Path of the Url : " + path);
   System.out.println("Query of the Url : " + query);
   System.out.println("Protocol of the Url : " + protocol);
   System.out.println("Authority of the Url : " + authority);
   System.out.println("Reference of the Url : " + reference);

  } catch (IOException ex) {
   ex.printStackTrace();

  } 
 }
}




Output of the program :



A simple Java program to read and download a Web page in a html file

Program to demonstrate how to read and download a webpage in a html file, in Java

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

public class UrlDownload {

   public static void main(String[] args) {

      try {
 // Create a URL object and pass url as string
 // to download the webpage 
 // 
 URL url = new URL("http://www.hubberspot.com");
 // Create a BufferedReader Object and pass it with
 // InputStreamReader Object containing an InputStream
 // Object retrieved  from openStream() method of URL
 BufferedReader reader = new BufferedReader
                      (new InputStreamReader(url.openStream()));
 // Create a BufferedWriter Object and pass it with
 // FileWriter Object containing an String
 // representing the file name to which 
 // the webpage is to download. 
 BufferedWriter writer = new BufferedWriter
                      (new FileWriter("hubberspot.html"));
 // Create a String object to read each line 
 // one by one from the stream
 String line;
 // looping till there is no line left to download
 while ((line = reader.readLine()) != null) {
 // Writing each line in the document hubberspot.html 
     writer.write(line);
     // to print each line on next line 
     writer.newLine();
 }
 // Closing the BufferedReader and BufferedWriter object 
 // to free the expensive resources
 reader.close();
 writer.close();
 }// handling two exceptions below 
 // In case URL is malformed MalformedURLException
 // Exception is thrown and 
 // IOException for any input/output failure
    catch (MalformedURLException e) {
 
 e.printStackTrace();
   } catch (IOException e) {
 
 e.printStackTrace();
  }
 }

}




Output of the program :



Creating a simple Chat Client/Server Solution in Java

Program to create a simple Chat Client/Server Solution in Java

1. Implementing a Chat Server

package com.hubberspot.examples;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

   private ServerSocket server;
   private int port = 5600;

   public Server() {
      try {
	server = new ServerSocket(port);
      } catch (IOException e) {
	   e.printStackTrace();
	}
   }

   public static void main(String[] args) {
	Server server = new Server();
	server.connection();
   }

   public void connection() {
	System.out.println("Waiting for client ...");
	try
	{
           Socket socket = server.accept();
	   System.out.println("Client accepted: " + socket);

	   DataInputStream dis = new DataInputStream(
		new BufferedInputStream(socket.getInputStream()));

	   boolean done = false;
	   while (!done)
	   {  
		try
		{  
	           String line = dis.readUTF();
		   System.out.println(line);
		   done = line.equals("bye");
		}
		catch(IOException ioe)
		{  
		   done = true;
		}
           }
	 	dis.close();				
		socket.close();
	   }
	   catch(IOException ioe)
	   {  
		System.out.println(ioe); 
	   }

    }
}



2. Implementing a Chat Client

package com.hubberspot.examples;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class Client {
   public static void main(String[] args) {
      try {
	//
	// Create a connection to the server socket on the server application
	//
	
        InetAddress host = InetAddress.getLocalHost();
	Socket socket = new Socket(host.getHostName(), 5600);

	//
	// Send a message to the client application
	//
	DataOutputStream dos = new DataOutputStream(
            socket.getOutputStream());
	
        DataInputStream dis = new DataInputStream(System.in);

	String line = "";
	while (!line.equals("bye"))
	{  
	   try
	   {  
		line = dis.readLine();
	        dos.writeUTF(line);
		dos.flush();
	   }
	   catch(IOException ioe)
	   {  
		System.out.println("Sending error: " + ioe.getMessage());
				}
	   }
	   
           dis.close();
	   dos.close();
	} catch (UnknownHostException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
   }
}



Output of the program : Client Screen

















Output of the program : Server Screen 



How to connect to a remote server through a Java program ?

Program to demonstrate a way to connect to a remote server by a simple Java program

package com.hubberspot.networking.example;

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

public class RemoteConnection {
  public static void main(String[] args) {
    String host = "tock.usno.navy.mil";
  
    try {
      Socket socket = new Socket(host, 13);
      InputStream timeStream = socket.getInputStream( );
      StringBuffer time = new StringBuffer( );
      int c;
      while ((c = timeStream.read( )) != -1) 
        time.append((char) c);
      String timeString = time.toString().trim( );
      System.out.println("It is " + timeString + " at "
        + host);
    } 
    catch (UnknownHostException e) {
      System.err.println(e);
    }
    catch (IOException e) {
      System.err.println(e);
    }
  } 
} 

Output of the program :

It is Thu May 3 17:08:47 2012 at tock.usno.navy.mil

How to read information from Server Socket through TCP Client Socket ?.

Program to read information from Server Socket through TCP Client Socket

package com.hubberspot.networking.example;

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

public class MyServerSocket
{
  public static void main(String args[]) 
 throws UnknownHostException, IOException
  {
    ServerSocket ss=new ServerSocket(4444);
    System.out.println("Server Started");
    Socket s = ss.accept(); 

  }
}


package com.hubberspot.networking.example;

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

public class MyClientSocket
{
  public static void main(String args[]) 
  { 
    try{
      InetAddress addr = InetAddress.getByName("localhost");
      Socket s=new Socket (addr, 4444);
      System.out.println (s.getInetAddress());
      System.out.println (s.getPort());
      System.out.println (s.getLocalPort());
      s.close();
    }
     catch(Exception e)
       { e.printStackTrace(); }
  }
}


First compile both files. Run the server and run the client program.

Output of the program :



How to use java.net.URLConnection Class for Java Networking ?.

Program to demonstrate working of URLConnection class and the methods of the URLConnection class for Java Networking

package com.hubberspot.networking.example;

import java.net.*;
import java.io.*;
import java.util.Date;
class URLConnectionExample
{
  public static void main(String args[]) throws Exception 
  {
    int ch;
    URL url = new URL("http://www.gmail.com");
    URLConnection connection = url.openConnection();

    System.out.println("Date: " + 
    new Date(connection.getDate()));
  
    System.out.println("Content-Type: " +
    connection.getContentType());
  
    System.out.println("Expires: " + 
    connection.getExpiration());
  
    System.out.println("Last-Modified: " + 
    new Date(connection.getLastModified()));
  
    int len = connection.getContentLength();
    System.out.println("Content-Length: " + len);

    if (len > 0) {
 System.out.println("===Print Content ===");
 InputStream input = connection.getInputStream();
 int i = len;
 while (((ch = input.read()) != -1) && (--i > 0)) {
  System.out.print((char) ch);
 }
 input.close();

 } else {
  System.out.println("No Content Available");
 }
 }
}


Output of the program :


How to use java.net.URL Class for Java Networking ?.

Program to demonstrate working of URL class and the methods of the URL class for Java Networking

package com.hubberspot.networking.example;

import java.net.*;

public class URLExample
{
  public static void main(String args[]) 
    throws MalformedURLException
  {

    URL url = new URL ("http://www.hubberspot.com/" +
   "p/introduction-to-java.html");

    System.out.println("Protocol is:" + url.getProtocol()); 
    System.out.println("Port is:" + url.getPort()); 
    System.out.println("Host is:" + url.getHost()); 
    System.out.println("File is:" + url.getFile()); 
  }
}

Output of the program :


How to use java.net.InetAddress Class for Java Networking ?.

Hello friends,
Today I am presenting to you with a Java program which deals with Networking. It demonstrates functioning of java.net.InetAddress class in Java. This Class has many powerful methods which can provide Java developer a powerful API. One of the important method is getLocalHost( ). This method displays the local host address over the console. The User can also print the name of address by calling getByName method. This method takes an parameter of String which is the name of the domain name for which we want the name.
Program to demonstrate working of InetAddress class and the methods of the InetAddress class for Java Networking

package com.hubberspot.networking.example;

import java.net.*;

public class InetAddressDemo
{

  public static void main(String[] args) 
  {
   try
   { 
     InetAddress address = InetAddress.getLocalHost();
     System.out.println("Local host's address : "
                     + address);
     address = InetAddress.getByName("www.google.com");
     
     System.out.println("Google's address : "
                     + address);

     InetAddress[] allAddresses = InetAddress
          .getAllByName("www.google.com");
     
     for( int i=0 ; i < allAddresses.length ; i++)
       System.out.println("Address " + i+1 + " : "
                    + allAddresses[i]);
  }
   catch(UnknownHostException    e)
   {
      e.printStackTrace();
   }
 }   
}


Output of the program :


 
© 2021 Learn Java by Examples Template by Hubberspot