Showing posts with label java programming. Show all posts
Showing posts with label java programming. Show all posts

Sunday

DatagramSocket



The java.net.DatagramSocket class has three constructors:
 public DatagramSocket() throws SocketException
 public DatagramSocket(int port) throws SocketException
 public DatagramSocket(int port, InetAddress laddr) throws SocketException
The first is used for datagram sockets that are primarily intended to act as clients; that is sockets that will send datagrams before receiving any.
The secned two that specify the port and optionally the IP address of the socket, are primarily intended for servers that must run on a well-known port.
The LocalPortScanner developed earlier only found TCP ports. The following program detects UDP ports in use.
import java.net.*;
import java.io.IOException;


public class NetparamScanner {

  public static void main(String[] args) {

    boolean rootaccess = false;
    for (int port = 1; port < 1024; port += 50) {
      try {
        ServerSocket ss = new ServerSocket(port);
        // if successful
        rootaccess = true;
        ss.close();
        break;
      }
      catch (IOException ex) {
      }
    }
   
    int startport = 1;
    if (!rootaccess) startport = 1024;
    int stopport = 65535;
   
    for (int port = startport; port <= stopport; port++) {
      try {
        DatagramSocket ds = new DatagramSocket(port);
        ds.close();
      }
      catch (IOException ex) {
        System.out.println("UDP Port " + port + " is occupied.");
      }
   
    }

  }

}
Since UDP is connectionless it is not possible to write a remote UDP port scanner. The only way you know whether or not a UDP server is listening on a remote port is if it sends something back to you.


Tuesday

TCP/IP Client example in Java


The Socket class is used for client connections. The client connects on the published port of the server. Please note the usage of InetAddress class in Socket constructor.
package com.netparam.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class JavaClient {

  public static void main (String[] args) {
   
    Socket socket = null;
    try {
      socket = new Socket(InetAddress.getLocalHost().getHostName(), 8888);
     
      // Reader and writer
      BufferedReader reader = new BufferedReader
          (new InputStreamReader(socket.getInputStream()));
      PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);

      // Write a message to server     
      writer.println("Hello from client");
     
      // Read message from server
      System.out.println(reader.readLine());     
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        socket.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

TCP/IP Server example in Java



Saturday

TCP/IP Server example in Java


The ServerSocket class is used to create servers. Typically we create the ServerSocket instance with the port number to be published for client connections. ServerSocket has the accept() method which waits for client connections. In the example below we use a ClientHandler thread which simply reads the message from client and writes back a message to client.
package com.netparam.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class JavaServer {

  private static class ClientHandler extends Thread {

    private Socket socket;
   
    ClientHandler(Socket socket) {
      System.out.println("Client connected");
      this.socket = socket;
    }
   
    @Override
    public void run() {
     
      try {
        // Reader and writer
        BufferedReader reader = new BufferedReader
            (new InputStreamReader(socket.getInputStream()));
        PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
       
        // Read message from client
        System.out.println(reader.readLine());
       
        // Write a message back to client
        writer.println("Hello from server");
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          socket.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
   
  }
 
  public static void main ( String[] args ) {
    final int port = 8888;
   
    try ( ServerSocket ss = new ServerSocket(port) ) {
      System.out.println("Listening ...");
      while ( true ) {
        Socket socket = ss.accept();
        new ClientHandler(socket).start();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}

Monday

Networking in Java


Java is a premier language for network programming. java.net package encapsulate large number of classes and interface that provides an easy-to use means to access network resources. Here are some important classes and interfaces of java.net package.

Some Important Classes
CLASSES
CacheRequest
CookieHandler
CookieManager
Datagrampacket
Inet Address
ServerSocket
Socket
DatagramSocket
Proxy
URL
URLConnection


Some Important Interfaces
INTERFACES
CookiePolicy
CookieStore
FileNameMap
SocketOption
InetAddress
ServerSocket
SocketImplFactory
ProtocolFamily


InetAddress
Inet Address encapsulates both numerical IP address and the domain name for that address. Inet address can handle both IPv4 and Ipv6 addresses. Inet Address class has no visible constructor. To create an inet Address object, you have to use Factory methods.
Three commonly used Inet Address factory methods are.
  1. static InetAddress getLocalHost() throws UnknownHostException
  2. static InetAddress getByName (String hostname) throws UnknownHostException
  3. static InetAddress[ ] getAllByName (String hostname) throws UnknownHostException



Example using InetAddress class
import java.net.*;
class Test
{
 public static void main(String[] args)
 {
  InetAddress address = InetAddress.getLocalHost();
  System.out.println(address);
  address = InetAddress.getByName("www.vigyancode.blogspot.com");
  System.out.println(address);
  InetAddress sw[] = InetAddress.getAllByName("www.vigyancode.blogspot.com");
  for(int i=0; i< sw.length; i++)
  {
   System.out.println(sw[i]);
  }
 }
}
Output:
Welcome-PC/59.161.87.227
www.netparam.com/74.125.236.115
www.netparam.com/74.125.236.116
www.netparam.com/74.125.236.112
www.netparam.com/74.125.236.113
www.netparam.com/74.125.236.114
www.netparam.com/2404:6800:4009:802:0:0:0:1014




Wednesday

Applet in Java



Applet is a predefined class in java.applet package used to design distributed application. It is a client side technology. Applets are run on web browser.

Advantage of Applet


  • · Applets are supported by most web browsers.
  • · Applets works on client side so less response time.
  • · Secured: No access to the local machine and can only access the server it came from.
  • · Easy to develop applet, just extends applet class.
  • · To run applets, it requires the Java plug-in at client side.
  • · Android, do not run Java applets.
  • · Some applets require a specific JRE. If it required new JRE then it take more time to download new JRE.


Life cycle of applet


  • · init()
  • · start()
  • · stop
  • · destroy

init(): Which will be executed whenever an applet program start loading, it contains the logic to initiate the applet properties.

start(): It will be executed whenever the applet program starts running.

stop(): Which will be executed whenever the applet window or browser is minimized.

destroy(): It will be executed whenever the applet window or browser is going to be closed (at the time of destroying the applet program permanently).

Design applet program

We can design our own applet program by extending applet class in the user defined class.

Syntax

class className extends Applet

{

......

// override lifecycle methods

......

}

Note: Whenever an applet program is running init() and start() will be executed one after another, but stop() and destroy() will be executed if the browser is minimized and closed by the end user, respectively.

Note: Applet program may or may not contain life cycle methods.

Running of applet programs

Applet program can run in two ways.


  • · Using html (in the web browser)
  • · Using appletviewer tool (in applet window)


Running of applet using html

In general no Java program can directly execute on the web browser except markup language like html, xml etc.

Html support a predefined tag called <applet> to load the applet program on the browser window.

Syntax

<applet code="udc.class">

height="100px"

width="100px"

</applet>

Example of applet program to run applet using html

//Java code, JavaApp.java

import java.applet.*;

import java.awt.*;

public class JavaApp extends Applet

{

public void paint(Graphics g)

{

Font f=new Font("Arial",Font.BOLD,30);

g.setFont(f);

setForeground(Color.red);

setBackground(Color.white);

g.drawString("Student",200,200);

}

}

//Html code, myapplet.html

<html>

<title> AppletEx</Title>

<body>

<applet code="JavaApp.class"

height="70%"

width="80%">

</applet>

</body>

</html>

If applet code not run on browser then allow blocked contents.



Running of applet using appletviewer

Some browser does not support <applet> tag so that Sun MicroSystem was introduced a special tool called appletviewer to run the applet program.

In this Scenario Java program should contain <applet> tag in the commented lines so that appletviewer tools can run the current applet program.

Example of Applet

import java.applet.*;
import java.awt.*;



/*<applet code="LifeApp.class" height="500",width="800">

</applet>*/



public class LifeApp extends Applet

{

String s= " ";

public void init()

{

s=s+ " int ";

}

public void start()

{

s=s+ "start ";

}

public void stop()

{

s=s+ "stop ";

}

public void destroy()

{

s=s+ " destory ";

}

public void paint(Graphics g)

{

Font f=new Font("Arial",Font.BOLD,30);

setBackgroundColor(Color."red");

g.setFont(f);

g.drawString(s,200,250);

}

}

Execution of applet program

javac LifeApp.java

appletviewer LifeApp.java

Note: init() always execute only once at the time of loading applet window and also it will be executed if the applet is restarted.