Send and Receive Message Using UDP in Java


//Program to send message using user datagram protocol in java. This program can send a single line message  at a time it is used on localhost. There one program name sender.java and Receiver.java. Sender program is used to send message and receiver program is used to receive program.

import java.io.*;
import java.net.*;
class sender
{
public static void main(String args[])
{
try
{
DatagramSocket sender = new DatagramSocket(2000);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true)
{
System.out.println("Enter the Message, Type end to terminate.");
String msg = br.readLine();
if(msg.equals("end"))
break;
DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(), InetAddress.getLocalHost(), 3000);
sender.send(packet);
System.out.println("Message successfully sent... ");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}


//Program to receive message using User Datagram Packet in java

import java.io.*;
import java.net.*;
class Receiver
{
public static void main(String args[])
{
try
{
DatagramSocket receiver = new DatagramSocket(3000);
System.out.println("Receiver is ready..., press ctrl + c to terminate... ");
while(true)
{
DatagramPacket packet = new DatagramPacket(new byte[1000], 100);
receiver.receive(packet);
String msg = new String(packet.getData());
System.out.println("Following message is received : "+msg.trim());
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}




DatagramSocket And DatagramPacket in java


DatagramSocket and DatagramPacket : Class facilitate connectionless networking between different clients. A datagram socket object provides object representation of UDP socket.
A DatagramSocket object can be creted using following constructors :-

        public DatagramSocket(int portno);
Commonly used methods are :-
send() :- Is used to send a UDP Packet.
public void send(DatagraPacket packet);

receive() :- Is used to receive a UDP packet.
public void receive(DatagraPacket packet);

close() :- Is used to close connection.
public void close();

DatagraPacket :- Class provides object representation of UDP packet. A DatagramPacket object can be created using eithere of the following constructors:

public DatagramPacket (byte[] data, int size, InetAddress ipadd, int receiveport);

public DatagramPacket(byte[] data, int size);

Commonly used methods are:-
getData() :- Returns the data of UDP packet as byteArray.

public byte[] getData[];

getPort() :- Returns the port number contains in a packet.

public int getPort();

getHost() :- Returns the IP address of host of a UDP packet.

etc...


Example : Send and Receive Message Using UDP in Java

If Condition

if condition

In shell script if condition is used in making decision , The command or given statement is executed if the condition is true.
Syntax:

if condition
then
command if condition is true or if exit status
of condition is 0 (zero)
...
...
fi

Condition can be defined as: "The if Condition is nothing but it is comparison between given two values."

For comparison we can use test or [ expr ] statements or even exist status can be also used in if condition.

Expression can be defined as: "An expression is the combination of values, relational operators like >,<, <> etc. and mathematical operators like +, -, / etc."

Given below are all example of expressions:
4 > 3
6 + 4
4 * 56
x < y
z > 7
z > 3 + 45 -23

Type following commands
$ ls
$ echo $?
The cat command returned the value zero(0) i.e. exit status, on successful execution of command, this can be used in if condition as follows, Write shell script as

$ cat > test.sh
if cat $1
then
echo -e "nnFile $1, found and successfully displayed the contents."
fi

Run above script as:
$ sh test.sh

Shell script name is test.sh ($0) and sunni is argument (which is $1).Then shell compare it as follows:
if cat $1 which is expanded to if cat sunni.


Socket Programming in java

Socket Programming using java.net.*; package.
This program is used to send a message to server from client side and send the acknowledgement from server to client side.

// Server.java


import java.io.*;
import java.net.*;
class Server
{
public static void main(String args[])
{
try
{
ServerSocket server = new ServerSocket(2000);
System.out.println("Server started waiting for connection request.... ");
Socket socket = server.accept();
System.out.println("Connection request received. Waiting for client message... ");
Thread.sleep(1000);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg = br.readLine();
System.out.println("Following message is received from client "+msg);
System.out.println("Sending acknowledgement");
System.out.println("Hello! Client your message has been received.");
Thread.sleep(3000);
System.out.println("Connection is closed.");
}
catch(Exception e)
{
System.out.println(e);
}
}
}


// client.java


import java.io.*;
import java.net.*;
class client
{
public static void main(String args[])
{
try
{
System.out.println("Client started requesting for connection.. ");
Socket socket = new Socket("localhost",2000);
System.out.println("Sending message to server...");
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println("Hello! Server.. ");
pw.flush();
System.out.println("Message has been sent to server.");
Thread.sleep(2000);
System.out.println("Waiting for acknowlegement.");
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())) ;
String msg = br.readLine();
System.out.println("Following message received from server "+msg);
System.out.println("Connection is closing... ");
socket.close();
System.out.println("Connection is closed.");
}
catch(Exception e)
{
System.out.println(e);
}
}
}



Socket Programming Tutorial


Socket : A socket is a logical end point of a connection from an application programmer point of view a socket is a process that is used by the application to send and receive data over network.
A socekt manage protocal specific details on behalf of the application. To facilitate concurrent communication using different protocls, concept of qoute was introduced.

Port : A port is a numbered socket. Port Number 0 to 1024 are reserved for standard protocol such as TCP/IP, HTTP, FTP, SMTP etc.


 java.net.Socket :- Class provides object representaion of TCP/IP socket that is a java application interact with TCP/IP socket through socket object. A socket object can be created using either of the following contructor.
Syntax : public Socket(String HostName, Int PortNo.)throws UnknownException,IOException;
Or
Syntax : public Socket(InetAddress Hostaddress, int portno)throws UnknownException, IOException;

Note:
First parameter of constructor represents either name of IP Address of the host on which TCP/IP server is running.
Let their be two machine name host A and host B on a network TCP/IP server is running on host B. Host A want to communicate with Host B using port 2000.



Methods of Socket Class are :-
getInputStream() : It returns an input stream to read socket data.
Syntax: public InputStream getInputStream();

getOutputStream() : Returns an outputstream to write data to socket.
Syntax: public OutputStream getOutputStream();

close() : Used to close a Socket.
Syntax: public void close();

OutputStream out = s.getOuputStream();

out.write("Hello $".getBytes());
---------------------------------------------------------------------
int n;
InputStream in = s.getInputStream();
StringBuffer str = new StringBuffer();
while(true)
{
if((n = in.read())!='$')
break;
else
str.append((char)n);
}
String s = str.toString();




PrintWriter p = new PrintWriter(s.getOutputStream());
p.print("Hello");


BufferedReader b = new BufferedReader(new InputStream(s.getInputStream());
String s = b.readLine();

java.net.ServerSocket :- Class represents the functionality of TCP/IP server. A server socket object can be created using either of the following contructor.
Syntax : public ServerSocket(int portno, int MAXQueueLenght);

Note: It's default length is 15.

accept() : Instructs the TCP/IP server to start listening connection request.
Syntax : public Socket accept();
close() :- close the TCP/IP server.
public void close();

Socket Programming in java Example.

Find IP Address of Machine


//Program to find the ip address of a given machine name.
import java.net.*;
class IPFinder
{
public static void main(String args[])
{
try
{
InetAddress add = InetAddress.getByName(args[0]);
System.out.println("Ipaddress of Machine is "+add.getHostAddress());
}
catch(Exception e)
{
System.out.println(e);
}
}
}


Use your Computer Name at the place of localhost to get your ip address.

Get the image size like height and width in PHP

To get the width and height of an image PHP provides a function getimagesize() this function determines the size of image file including flash file(swf).

Syntax
list($width, $height, $type, $attr) = getimagesize("image_name.jpg");

<?php
echo "<img src='http://webmastertrainings.in/images/2012/07/learn-php.png'></br></br>";
list($width, $height, $type, $attr) = getimagesize("http://webmastertrainings.in/images/2012/07/learn-php.png");

echo "Image width, height, type are :-"
echo "Width " .$width;
echo "<BR>";
echo "Height " .$height;
echo "<BR>";
echo "Type " .$type;
echo "<BR>";
echo "Image Attribute " .$attr;
?>



Type of Image are :-

1 = GIF 5 = PSD 9 = JPC 13 = SWC
2 = JPG 6 = BMP 10 = JP2 14 = IFF
3 = PNG 7 = TIFF(intel byte order) 11 = JPX 15 = WBMP
4 = SWF 8 = TIFF(motorola byte order) 12 = JB2 16 = XBM

Networking Tutorial in Java


java.net package contains classes and interfaces that provides networking support to the java application commonly used classes and interface of this package are :
InetAddress
Socket
ServerSocket
DatagramSocket
DatagramPacket

InetAddress This class provides object representation of public contructor rather it provides Factory method for creating its object.
Factory is a creational design pattern that is used to control creation of object. Imiplementation of this design pattern is proivded whti the help of factory class.

A Factory class is a class that contains factory method. A factory method is a method that creates and returns objects.

Singleton Class It is a class that can be instantiated only once.

Class A
{
private static A a = null;
private A()
{
-------------------
-------------------
-------------------
}
public satif A getA()
{
if(a==null)
{
a = new A();
}
return a;
}
}



A x = A.getA();
A x1 = A.getA();


Various Factory Method of InetAddress class are :

getLocalHost(); Returns an InetAddress object representing the IP Address of the current machine.
syntax:
public statif InetAddress getLocalHost()throws UnknownHostException;

Example: InetAddress add = InetAddress.getLocalHost();

getByName(); Returns an InetAddress object representing IP Address of the given machine.
syntax:
public static InetAddress getByName(String HostName)throws UnknownHostException;

getAllByName(); Returns an array of InetAddress object each element of an array represents an InetAddress of the given host.
syntax:
public static InetAddress[] getAllByName(String HostName)throws UnknownHostException;


Non-Factory Method of InetAddress Class

getHostAddress(); Returns IP Address as string public String getHostAddress();
syntax:
public String getHostAddress();

getHostName(); Returns HostName as a String.
syntax:
public String getHostName();


Example of : Find IP Address of Machine

Read from second file and append File to first file

Write a program that will take two file names from the command prompt and concatenate the second file at the end of first one.


import java.io.*;
public class AppendFile
{
    public static void main(String args[])
    {
        try
        {
File file = new File(args[0]);
FileReader fileReader =new FileReader(args[1]);
            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = new BufferedReader(fileReader);
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
            BufferedWriter bw = new BufferedWriter(fw);

            int i =0;
            // if file doesnt exists, then create it
            System.out.println("Writing to first file from the second file : ");
while((i = bufferedReader.read()) != -1)
{  
char ch = (char) i;
bw.write(ch);
}
            bw.close();
            System.out.println("Done");
            bufferedReader.close();          
        }
        catch(Exception ex)
        {
            System.out.println(ex);          
        }
    }
}


Use Of Pipes



The pipe is used to connect the output of one command line to take input in another command line.





Pipe Defined as:

"The pipe is nothing but is used as a temporary storage place where the output of one command line is stored and then it is passed as the input to the second command line. Pipes can be used to run more than two commands from at the same command line."

Syntax:
command1 | command2





Examples: 



Command using Pipes
Meaning or Use of Pipes
$ ls | more
The output of ls command is given as input to more command So that output will be printed one screen full page at a time and we’ll be able to use space bar to see next page.

$ who | sort
The output of who command is given as input to sort command So that it will print the output of users in alphabetical order.

$ who | sort > users_list
The output of the above command will be saved in file named users_list.

$ who | wc -l 
The output of the who command will be given as the input to wc command So that it could be display the number of user who is currently logged in to system.

$ ls -l | wc  -l   
The output of ls command will be given as input to wc command So that it will be able to print number of files in current directory available.

$ who | grep raju
The output of who command will be given to grep command as input So that it will able to print the output if a particular user name if he is currently logged in otherwise nothing will printed.

Variable Declaration and Initializing in JavaScript

1.    Values
Value is a piece of information that can be a number, string, Null, Boolean, Object, or a Function as listed below:

String: It is the series of characters inside double quotes (" ").
Example: "We are learning JavaScript"

Boolean: It is true or false value.
Example: false

Number: It can be any numeric value (without double or single quotes).
Example: 10.13

Null: It has no value.
Example: null

Object: Properties and methods of an object.


2.    Variables
Variable is a place holder or value holder in our computer's memory for information that can changed. This place in memory has been given a name in JavaScript so that we can easily refer to it. Declaring a variable is very easy. We have to do is precede the variable name with the word var as follows:

var variablename;

Once the variable is declared, then you can initialize it with any value shown above.
Here is an example:

variablename = 145.53;
Like the given above example you can change its value to different:

variablename = 65;

We can also change the type by simply assigning a different type of value. We can make this variable a string in the program by simply assigning it one as follows:

variablename = "This is a string in javascript.";

We can initialize a variable and assign it a value at the same time.
Example :
var variablename = "This is javascript.";

You will be using this method most of the time to declare and initialize variables.

I advice that you already try out some of these variables in a simple code like this one:

<html>
    <head>
        <title></title>
    </head>
    <body>
        <script language="JavaScript">
            var variablename = 547;
            document.write(variablename);
        </script>
    </body>
</html>
Now try to change the value of the variable into whatever you like:

<html>
    <head>
        <title>My first Script</title>
    </head>
    <body>
        <center>
            <h1>This Variable decaration and initializing example in JAVASCRIPT.</h1>
            <script language="JavaScript">

                var myVariable = "This is a string in javascript"; //String Type
                document.write(myVariable);
                document.write("<br>");
               
                myVariable = 1234;  // number Type
                document.write(myVariable);
                document.write("<br>");
               
                myVariable = true;  // Boolean Type
                document.write(myVariable);
                document.write("<br>");
               
                var myVariable = null;  // Null Type
                document.write(myVariable);
                document.write("<br>")
               
                myVariable = new Date;  // object Type
                document.write(myVariable);
                document.write("<br>");
           
            </script>
        </center>
    </body>
</html>

The Symbol (//) in given program is used to make single line comment.


Generate Random Numbers And write or read to file

import java.util.Random;
import java.io.*;
public class Test
{
    public static void main(String args[])
    {
        // The name of the file to open.
        String fileName = "temp.txt";
        char line[] = new char[64];
        try
        {
            File file = new File(fileName);
             // if file doesnt exists, then create it
            if (!file.exists())
            {
                file.createNewFile();
            }
             FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            System.out.println("Writing to File");
            Random randomGenerator = new Random();
            for (int idx = 1; idx <= 50; ++idx)
            {
                int randomInt = randomGenerator.nextInt(1000000);
                bw.write(String.valueOf(randomInt)+"n");
            }
            bw.close();

            System.out.println("Done");
            // FileReader reads text files in the default encoding.
            FileReader fileReader =new FileReader(fileName);
            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            System.out.println("Reading from file");
            int i =0, count =0;
            String l=null;
            while((i = bufferedReader.read()) != -1)
            {   
                char ch = (char) i;
                l = l + ch;
                count++;
                if(count==64)
                {
                    System.out.println("Length is "+count+"n");
                    System.out.print(l);
                    count=0;
                    l = "";
                }
            }   
       
            // Always close files.
            bufferedReader.close();           
        }
        catch(FileNotFoundException ex)
        {
            System.out.println("Unable to open file '" +fileName + "'");           
        }
        catch(IOException ex)
        {
            System.out.println("Error reading file '"+ fileName + "'");
        }
    }
}

Working with Cookie


1.     What is a Cookie?
Cookie is used to identify a user. It is a small file which is automatically get embedded by server on the user's computer or PC. Every time when the computer requests a page using browser it sends the cookie too. Using PHP we can create or retrieve cookie values.


2.      How to Create a Cookie?
In PHP the setcookie() function is used to create cookie.
Note: setcookie() must appear before the <html> tag.
Syntax:-

setcookie(cookiename, value, expiringtime, path, domainname);

Example:
Given example will create a cookie named "PHPCookie" and will assign the value "PHPUser". We'll also specify the cookie should expire after one hour too:

<?php
setcookie("PHPCookie", "PHPUser", time()+3600);
?>
<html>
......
        ......
Note: Value of the cookie will automatically URLencoded when sending the cookie and automatically decoded when received.


3.      How to Retrieve a Cookie Value?
To retrieve the cookie value PHP provides $_COOKIE variable in built.
Given below example will retrieve the value of cookie named "PHPCookie" and display it on a page:
<?php
// Print a cookie
echo $_COOKIE["PHPCookie"];
// To view all cookies
print_r($_COOKIE);
?>
In this example we'll use the isset() function to find out if a cookie has been set or not:
<html>
<body>
<?php
if (isset($_COOKIE["PHPCookie"]))
echo "Welcome " . $_COOKIE["PHPCookie"] . "!<br>";
else
echo "Welcome guest!<br>";
?>
</body>
</html>


4.     How to Delete a Cookie?
To delete a cookie we should assure that the expiration date is in the past. Otherwise it'll through the error.
Example to Delete Cookie:
<?php
// set the expiration date to one hour ago
setcookie("PHPCookie", "", time()-3600);
?>



Get Class Description Using Methods of java.lang.Class


/*Program to get details of a class given on command line argument*/
import java.lang.reflect.*;
class Descriptor
{
public static void main(String args[])
{
try
{
Class c = Class.forName(args[0]);
Field f[] = c.getDeclaredFields();
System.out.println("Various Fields of class are : ");
for(int i = 0;i<f.length;i++)
{
System.out.println(f[i]);
}
Constructor ctr[] = c.getDeclaredConstructors();
System.out.println("Various Constructors of class are : ");
for(int i = 0;i<ctr.length;i++)
{
System.out.println(ctr[i]);
}
Method m[] = c.getDeclaredMethods();
System.out.println("Various methods of class are : ");
for(int i=0;i<m.length;i++)
{
System.out.println(m[i]);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}