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.