Pages

Tuesday, May 29, 2012

Datagram Client in Java

This Example is implementation of Datagram Client or UDP client purpose of this example is to provide a fare idea about the working of UDP client server this client example works with server example and link to server example is given at the end of this code example works on the concept of UDP protocol (simple transmission model without implicit handshaking)



-Watch video
https://youtu.be/sX0XAROhuiQ
import java.io.*;

import java.net.*;

public class Client {

    public static void main(String[] args) {

      DatagramSocket clientSkt = null;

      InetAddress IPAdd = null;

      String text =null;

      DatagramPacket receivePkt= null;

      BufferedReader inFromUser =

         new BufferedReader(new InputStreamReader(System.in));

      try{

      clientSkt = new DatagramSocket();

      IPAdd = InetAddress.getByName("localhost");

      }

      catch(SocketException exp){

          System.out.println(exp);

      }

      catch(UnknownHostException exp){

          System.out.println(exp);

      }      

      byte[] sendData = new byte[1024];

      byte[] receiveData = new byte[1024];

      try{

      text = inFromUser.readLine();

      sendData = text.getBytes();

      DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAdd, 3030);

      clientSkt.send(sendPacket);

      receivePkt = new DatagramPacket(receiveData, receiveData.length);

      clientSkt.receive(receivePkt);

      }

      catch(IOException exp){

          System.out.println(exp);

      }

      String modifiedSentence = new String(receivePkt.getData());

      System.out.println("FROM SERVER:" + modifiedSentence);

      clientSkt.close();

    }

}
Watch video
Datagram Server Source

Datagram Server in Java

This example is about Datagram Server or UDP server purpose of this example is to provide a fare idea about the working of UDP client server this server example works with client example and link to the client example is given at the end of this code example works on the concept of UDP protocol (simple transmission model without implicit handshaking)

Play Free Online Games and Win Big Prize Money 

-Watch video
https://youtu.be/sX0XAROhuiQ
import java.io.*;

import java.net.*;

public class Server {

    public static void main(String[] args) {

        DatagramSocket serverSkt= null;

        try{

            serverSkt = new DatagramSocket(3030);

        }

        catch(SocketException exp)

        {

            System.out.println(exp);

        }

        byte[] receiveData = new byte[1024];

        byte[] sendData = new byte[1024];

        while(true)

          {

            DatagramPacket receivePkt = new DatagramPacket(receiveData, receiveData.length);

            try{

                serverSkt.receive(receivePkt);

            }

            catch(IOException exp)

            {

                System.out.println(exp);

            }

            String sentence = new String( receivePkt.getData());

            System.out.println("RECEIVED: " + sentence);

            InetAddress IPAddress = receivePkt.getAddress();

            int port = receivePkt.getPort();

            String capitalizedSentence = sentence.toUpperCase();

            sendData = capitalizedSentence.getBytes();

            DatagramPacket sendPkt =

            new DatagramPacket(sendData, sendData.length, IPAddress, port);

            try{

            serverSkt.send(sendPkt);

            }

            catch(IOException exp)

            {

                System.out.println(exp);

            }   

        }

      }        

  }
Watch video
Datagram Client Source

Friday, February 10, 2012

Get Your PC's IP Address in Java

This example returns IP address of your PC.

Play Free Online Games and Win Big Prize Money 

-Watch video
https://youtu.be/sX0XAROhuiQ
import java.net.*;

public class TellMyIP {

public static void main(String[] args) {

 InetAddress localHostIP= null;

   //creates instance of InetAddress

  try{

  localHostIP=InetAddress.getLocalHost();

  //initializes localHostIP

  System.out.println("IP ADDRESS OF MY PC IS = "+localHostIP.getHostAddress());

  //gets IP address and prints it

  }catch (Exception exception){

  System.out.println("Something that went wrong is :"+exception.getMessage());

  }

   }

}
Watch video

Wednesday, March 30, 2011

Send email in Java with attachment

Java Mail API is required to work with this code to send email in Java from your email account with attachments .

       
import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.*;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class MailWithAttachment

{

public static void main(String args[]) throws Exception

{

    String host = "smtp.gmail.com";//host name

    String from = "abc@gmail.com";//sender id

    String to = "xyz@yahoo.com";//reciever id

    String pass = "***";//sender's password 

    String fileAttachment = "test.txt";//file name for attachment 

    //system properties

    Properties prop = System.getProperties();

    // Setup mail server properties

    prop.put("mail.smtp.gmail", host);

    prop.put("mail.smtp.starttls.enable", "true");

    prop.put("mail.smtp.host", host);

    prop.put("mail.smtp.user", from);

    prop.put("mail.smtp.password", pass);

    prop.put("mail.smtp.port", "587");

    prop.put("mail.smtp.auth", "true");

    //session 

    Session session = Session.getInstance(prop, null);

    // Define message

    MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(from));

    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));

    message.setSubject("Hello Java Mail Attachment");

    // create the message part 

    MimeBodyPart messageBodyPart = new MimeBodyPart();

    //message body

    messageBodyPart.setText("Hi");

    Multipart multipart = new MimeMultipart();

    multipart.addBodyPart(messageBodyPart);

    //attachment

    messageBodyPart = new MimeBodyPart();

    DataSource source = new FileDataSource(fileAttachment);

    messageBodyPart.setDataHandler(new DataHandler(source));

    messageBodyPart.setFileName(fileAttachment);

    multipart.addBodyPart(messageBodyPart);

    message.setContent(multipart);

    //send message to reciever

    Transport transport = session.getTransport("smtp");

    transport.connect(host, from, pass);

    transport.sendMessage(message, message.getAllRecipients());

    transport.close();

}

}
Watch video

Monday, March 28, 2011

Database Connctions in Java

This example Works with MS Access to explain DB concepts and can be changed accordingly to any other database for that you will need to configure their respective JAR libraries to your project i.e. for MY-SQL you will need MySQL-Connector JAR.

       
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class dbConnections

{

public static void main(String args[])

{

     try{  

      Class.forName("sun.jdbc.odbc.JdbcOdbc");  //load DB drivers

      Connection con=DriverManager.getConnection("jdbc:odbc:DBName",username,pwd);

      //create db connections

      Statement stmt = con.createStatement(); // creates statement for db access

      String query = "SELECT * FROM Job"; // sql query

      ResultSet rs = stmt.executeQuery(query);

      //execute sql query and stores the result in the result set rs

      while( rs.next() ) {

       System.out.println("Job  "+rs.getString("Job_Id"));

      }

      rs.close(); //close resultset

      stmt.close(); // close statement 

      con.close();  // close connection   

     }

    catch(SQLException e)

    {

     System.out.println(e);

    }

    catch(ClassNotFoundException e)

    {

     System.out.println(e);

   }

}

}
Watch video

Wednesday, March 16, 2011

Read emails from Gmail Account

This code reads emails from a Gmail account to work with this code you will need javax.mail API
-Watch video


https://youtu.be/sX0XAROhuiQ
import java.io.BufferedInputStream;

import java.io.IOException;

import java.io.FileWriter;

import java.io.InputStream;

import java.security.*;

import java.util.Properties;

import javax.mail.*;

public class ReadMail {

  public static void main(String args[]) throws IOException {

         Properties properties = System.getProperties();

         properties.setProperty("mail.store.protocol", "imaps");

             try {

                 Session session = Session.getDefaultInstance(properties, null);

                 //create session instance

                 Store store = session.getStore("imaps");//create store instance

                 store.connect("pop.gmail.com", "abc@gmail.com", "****");

                 //set your user_name and password

                 System.out.println(store); 

                 Folder inbox = store.getFolder("inbox");

                 //set folder from where u wants to read mails

                 inbox.open(Folder.READ_ONLY);//set access type of Inbox

                 Message messages[] = inbox.getMessages();// gets inbox messages

                 for (int i = 0; i < messages.length; i++) {

                System.out.println("------------ Message " + (i + 1) + " ------------");

                System.out.println("SentDate : " + messages[i].getSentDate()); //print sent date

                System.out.println("From : " + messages[i].getFrom()[0]); //print email id of sender

                System.out.println("Sub : " + messages[i].getSubject()); //print subject of email

                try

                {

                      Multipart mulpart = (Multipart) messages[i].getContent();

                      int count = mulpart.getCount();

                      for (int j = 0; j+1 < count; j++)

                     {

                          storePart(mulpart.getBodyPart(j));

                     }

                }

                catch (Exception ex)

                {

                     System.out.println("Exception arise at get Content");

                     ex.printStackTrace();

                }

           }

           store.close();

      }

catch (Exception e) {

System.out.println(e);  

}  

}

  public static void storePart(Part part) throws Exception

     {    

          InputStream input = part.getInputStream();

          if (!(input instanceof BufferedInputStream))

         {

              input = new BufferedInputStream(input);

          }

          int i;

         System.out.println("msg : ");

          while ((i = input.read()) != -1)

         {

         System.out.write(i);

         }

     }

}
Watch video
Send email using javax.mail source

Wednesday, January 19, 2011

Telnet Client with Java

This example implements Telnet with help of Telnet server. The code connects to the Telnet server and receives data whenever command "1" is entered


Watch video
https://youtu.be/sX0XAROhuiQ
import java.net.*;

import java.io.*;

class TelnetClient

{

    public static void main(String args[]) throws Exception

    {

        //Create object of Socket

        Socket soc=new Socket("localhost",8088);

        String Command;

        //Create object of Input Stream to read from socket

        DataInputStream din=new DataInputStream(soc.getInputStream());    

        //Create object of Output Stream   to write on socket 

        DataOutputStream dout=new DataOutputStream(soc.getOutputStream());

        // Object of Buffered Reader to read command from terminal

        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Welcome to Telnet Client");

        System.out.println("< Telnet Prompt >");

        Command=br.readLine();//reads the command 

        dout.writeUTF(Command);//sends command to server

        System.out.println(din.readLine()); //gets the response of server        

        soc.close();  //close port  

        din.close();  //close input stream     

        dout.close();  //close output stream      

        br.close();   //close buffered Reader    

    }

}
Watch video
Telnet Server Source