Pages

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

Telnet Server with Java

This code sends a string to a client whenever client connects it and sends the response to client when command "1" is received.


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

import java.io.*;

import java.net.*;

class TelnetServer {

   public static void main(String args[]) {

      String data = "Hello Client!! ";

      try {

          // Create object of Server Socket 

         ServerSocket srvr = new ServerSocket(8088);

          // Socket object that listens the port (8088) and accepts the incoming connection

          //requests 

         Socket skt = srvr.accept();

         System.out.println("Client Connected!");

         // gets output stream object  

         PrintWriter out = new PrintWriter(skt.getOutputStream(), true);

         //gets input stream object    

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

         if(din.readUTF().equals("1")){ 

         // sends response to incoming request if command is '1'    



         System.out.println("String: '" + data);

         out.print(data);

         }

         out.close();// clos out

         skt.close();// close skt

         srvr.close();// close srvr

         din.close(); // close din

      }

      catch(Exception e) {

         System.out.print(e);

      }

   }

}
Watch video
Telnet Client Source

Thursday, January 13, 2011

Reading and Writhing Data from comm port in Java

This code first write 0x80 to COM port then it reads 0x32 from COM port and then sends 6 more bytes and to terminate the packet it sends 0x70.

import java.io.*;
import java.util.*;
import javax.comm.*;
import java.sql.Connection;
import  java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class Fms implements Runnable{ 
    static Enumeration portList;
    static CommPortIdentifier portId;
    static SerialPort serialPort;
    static OutputStream outputStream;
    static InputStream inputStream;
    static Thread readThread,dataBase;
    static int crf;
    static int cwf;
    static byte cxc[] = new byte[4];
    static int cxm = 128;//0x80
    static byte[] creadBuffer;//1byte read
    static int creadBuff[]; 
    write rt=new write();
    static read rd;   
     public void run() {
     };
    public static void main(String[] args) {
        int a=10;
        write wr = new write();
        read rd = new read(1);
         int b = 0;
        int speed=0,tcount=0,jcount=0,status=0;
      while(b!=10){      
       for(int j =0 ; j<=1;j++){
            try{
        wr.cwritemain(a); 
         rd.cmainx(a);          
         readThread.sleep(1000);
            }
            catch(Exception e){}
            if(j==0){
                status =creadBuff[1];
                jcount =creadBuff[5];
          System.out.println("results : "+status +"\t"+jcount); 
            }
            if(j==1){
                speed =creadBuff[1]*256+creadBuff[2];//to convert received data in decimal
                tcount =creadBuff[6];
          System.out.println("results : "+speed +"\t"+tcount); 
            }
             }    
    }            
       }
 static class write{        
         public void cwritemain(int m)
{       
             cwf = m;
             cxc[0] = 0x26;
             portList = CommPortIdentifier.getPortIdentifiers();
             System.out.println(portList.hasMoreElements());
while (portList.hasMoreElements()) {                                   
                                        portId = (CommPortIdentifier) portList.nextElement();
                                        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                                    
if (portId.getName().equals("COM1"))
{                                  
try {
serialPort = (SerialPort) portId.open("SimpleWriteApp32", 2000);
                                                  } catch (PortInUseException e) {
}
try {
outputStream = serialPort.getOutputStream();
} catch (Exception e) {
}
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (Exception e) {
}
                                               if(cwf==10){
try {
outputStream.write(cxm);// 0x80 written
serialPort.close();
                                                                outputStream.close();
} catch (Exception e) {
}
                                               }
                                        }
                                }
                        }
         }        
    }   
   static class read implements SerialPortEventListener{
      public read(int s) {}
      public void cmainx(int cp) {
crf = 10;
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
try {
                                                    serialPort = (SerialPort) portId.open("readapp32",
2000);
} catch (PortInUseException e) {
System.out.println(e.getMessage());
}
try {
inputStream = serialPort.getInputStream();
} catch (Exception e) {
System.out.println(e);
}
try {
serialPort.addEventListener(this);
} catch (Exception e) {
System.out.println(e);
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);                                                
} catch (Exception e) {
System.out.println(e);
}
}
}
}                       
}
        public void serialEvent(SerialPortEvent event) {            
            switch (event.getEventType()) {
case SerialPortEvent.DATA_AVAILABLE:
creadBuffer = new byte[8];
                                creadBuff= new int[8];
try {
                                   int i = 0;                               
while (inputStream.available() > 0) { 
                                          creadBuff[i]=inputStream.read();
                                          System.out.println("Data available is: "+creadBuff[i]);                                                  
                                               i++;
}
                                      inputStream.close();
} catch (IOException e) {
}
                                System.out.println("event");
System.out.println("recieved \t"+creadBuffer[0] );
if (creadBuffer[0] == 0x70) {
                                    System.out.println("Got 0x70"+creadBuffer[0] );
serialPort.close();
rd = new read(5);
rd.cmainx(1);// ag
                                }
                                if (creadBuffer[0] == 0x32) {
                                    System.out.println("Got"+creadBuffer[0] );
serialPort.close();                                
                                }
                                serialPort.close();
            }
        }
   }  
   }
Watch video

Saturday, January 8, 2011

Send email in Java

//javax.mail
This code sends mail using gmail smtp you may need javax.mail api to implement this code.


-Watch video
https://youtu.be/sX0XAROhuiQ
import java.util.Properties;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.Message.RecipientType;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeMessage;

import javax.mail.Store;

public class Main {

        public static void main(String[] args) {

try{

                    String host = "smtp.gmail.com";

                    String from = "abc@gmail.com";//your gmail account

                    String pass = "****";//your password of gmail account

                    Properties props = System.getProperties();

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

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

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

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

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

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

                    String[] to = {"xyz@gmail.com"};

                    // receiver mail address can be other then gmail

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

                    MimeMessage message = new MimeMessage(session);

                    message.setFrom(new InternetAddress(from));

                    InternetAddress[] toAddress = new InternetAddress[to.length];

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

                        toAddress[i] = new InternetAddress(to[i]);

                    }

                    System.out.println(Message.RecipientType.TO);

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

                        message.addRecipient(Message.RecipientType.TO, toAddress[i]);

                    }

                    message.setSubject("Java Mail!!!");//set subject of mail

                    message.setText("Hey!!! This is mail from your friend Java!!");//set mail content

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

                    transport.connect(host, from, pass);

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

                    transport.close();

                    }

                        catch(Exception e)

                    {

                        System.out.println(e);

                    }   

 }        

}
Watch video