Saturday, January 11, 2014

Sending and receiving Java Objects through network Java Program [Advanced]

/* Program for Server1 */
import java.io.*;
import java.net.*;
class Server1
{
public static void main(String args[])
{
ServerSocket ss;
Socket s;
ObjectOutputStream oos;
ObjectInputStream ois;
String st;
BufferedReader br;
try
{
ss=new ServerSocket(7070);
System.out.println("Server is register at 7070 port ");
while(true)
{
s=ss.accept();
ois=new ObjectInputStream(s.getInputStream());
System.out.println("Client Msg : " + (String)ois.readObject());
System.out.println("Server Msg : ");
br=new BufferedReader(new InputStreamReader(System.in));
st=br.readLine();
oos=new ObjectOutputStream(s.getOutputStream());
oos.writeObject(st);
}
}catch(Exception e)
{
System.out.println("Error : " + e);
System.exit(0);
}
}
}

------------------------------------------------------------------------------------------------------------------


/* Program for Client1 */
import java.io.*;
import java.net.*;
class Client1
{
public static void main(String args[])
{
Socket client;
ObjectInputStream ois;
ObjectOutputStream oos;
String s;
BufferedReader br;
try
{
client=new Socket("localhost",7070);
ois=new ObjectInputStream(client.getInputStream());
s=(String)ois.readObject();
System.out.println("Server : " + s);
System.out.println("Client : " );
br=new BufferedReader(new InputStreamReader(System.in));
s=br.readLine();
oos=new ObjectOutputStream(client.getOutputStream());
oos.writeObject(s);
}catch(Exception e)
{
System.out.println("Error : " + e);
System.exit(0);
}
}
}



Post a Comment