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

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




Saturday

Synchronized Keyword in Java


Synchronized Keyword is used for when we want to allowed only one thread at a time then use Synchronized modifier. If a method or block declared as a Synchronized then at a time only one thread is allowed to operate on the given object.
Synchronized is a Modifier which is applicable for the method or block, we can not declare class or variable with this modifier.
Advantage of Synchronized
The main advantage of Synchronized keyword is we can resolve data inconsistency problem.
Dis-Advantage of Synchronized
The main dis-advantage of Synchronized keyword is it increased the waiting time of thread and effect performance of the system, Hence if there is no specific requirement it is never recommended to use synchronized keyword.


Command Line Arguments in Java


If any input value is passed through the command prompt at the time of running of the program is known as command line argument by default every command line argument will be treated as string value and those are stored in a string array of main() method.

Syntax for Compile and Run CMD programs
Compile By -> Javac  Mainclass.java
Run By -> Java  Mainclass value1 value2  value3 ....................


Example of command-line argument in java
class CommandLineExample
{
public static void main(String args[])
{ 
System.out.println("Argument is: "+args[0]);
} 
} 
Compile and Run above programs
Compile By > Javac  CommandLineExample.java
Run By > Java  CommandLineExample Porter
Output
Argument is: Porter
Example of command-line argument in java
class SumDemo
{
public static void main(String args[])
{ 
System.out.println("Sum: "+args[0]);
} 
} 
Compile and Run above programs
Compile By > Javac  SumDemo.java
Run By > Java  SumDemo 10 20
Output
Sum: 30
When the above statement is executing the following sequence of steps will take place.
·         Class loader sub-system loads SumDemo along with Command line argument(10, 20) and in main memory.
·         JVM takes the loaded class SumDemo along with Command line arguments (10, 20) and place the number of values in the length variable that is 2.
·         JVM looks for main() that is JVM will place the Command in the main() in the form of string class that is.

·         Hence all the CMD line arguments of Java are sending to main() method available in the form of an array of object of String class (every CMD are available or stored in main method in the form of an array of object of String class).
·         JVM calls the main() method with respect to load class SumDemo that is SumDemo.main().

Accept command line arguments and display their values
class  CMD
{
public static void main(String k[])
{
System.out.println("no. of arguments ="+k.length);
for(int i=0;i< k.length;i++)
{
System.out.println(k[i]);
}
}
}

Note: Except + operator any numeric operation not allowed in command line arguments.

Square of Number by reading value from command prompt.
class squareDemo
{
int no, result;
void square(String s)
{
int no=Integer.parseInt(s);
result=no*no;
System.out.println("Square: " +result);
}
}
class CMD
{
public static void main(String args[])
{
System.out.println("no of arguments: "+args.length);
squareDemo  obj=new  squareDemo();
obj.square(args[0]);
}
}