Wednesday, December 1, 2010

Pin It


Get Gadget

After some reading I found This is the most easiest way to transfer data in client-server application in Java.





This is the normal way of a Sever Side of the application;

import java.net.ServerSocket;    
import java.net.Socket;    
import java.io.IOException;    
import java.io.InputStreamReader;    
import java.io.BufferedReader;    
import java.lang.System;        
public class server    {      
public static void main (String args[]) throws IOException {
  ServerSocket s = new ServerSocket (2000);        
  Socket sock;        
  BufferedReader datain;            
  System.out.println ("Server starting ...");        
  sock = s.accept ();            
  datain = new BufferedReader (new InputStreamReader(sock.getInputStream ()));        
  System.out.println (datain.readLine ());            
  sock.close ();        
  s.close ();      
}    
}
This is the normal way of a Client Side of the application;
import java.net.Socket;    
import java.net.InetAddress;    
import java.io.IOException;    
import java.io.OutputStreamWriter;    
import java.io.BufferedWriter;    
import java.lang.System;        
public class client{      
public static void main (String args[])throws IOException {        
  Socket sock = new Socket (InetAddress.getLocalHost (), 2000);        
  BufferedWriter dataout;        
  String Message = "Howdy!";            
  System.out.println ("Sending "+ Message + " ...");            
  dataout = new BufferedWriter (new OutputStreamWriter (sock.getOutputStream ()));        
  dataout.write (Message, 0, Message.length ());        
  dataout.flush ();            
  sock.close ();      
}    
}

But think a situation where we have to transfer set of data at a time. For a example like details of a
Student registration. So When we use normal method we have to send data fields as messages. Example name 
one time , age at one time so and so But we can use java class to over come this problem.

Hear is a example.
Server Side;

import java.io.*;
import java.util.Date;
public class SaveDate {
public static void main(String argv[]) throws Exception {
FileOutputStream fos = new FileOutputStream("date.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
Student st = new Student();
oos.writeObject(st);
oos.flush();
oos.close();
fos.close();
}
}
Client Side ;
import java.io.*;
import java.util.Date;
public class ReadDate {
public static void main(String argv[]) throws Exception {
FileInputStream fis = new FileInputStream("date.out");
ObjectInputStream ois = new ObjectInputStream(fis);
Student st = (Student) ois.readObject();
System.out.println("The Name is:"+st.name);
System.out.println("The Index is:"+st.index);
ois.close();
fis.close();
}
}
The Student Class;

public Students implements Serializble{
  String name;
  String index
}

No comments:

Post a Comment