Wednesday, June 20, 2012

Client Server Communication in Android


Here the client is the android mobile and java app is acting as the server. The client code snippet is as follows:

Socket sock=null;
       PrintStream ps=null;
System.out.println(" Trying to connect");
                       
       try
       {
              InetAddress ip =InetAddress.getByName("localhost");
              sock=new Socket("112.207.67.208",1052);//give the ip and port no:
              PrintWriter out = new PrintWriter(new BufferedWriter(new
              OutputStreamWriter (sock.getOutputStream())), true);
               out.println(“Hellooo…”);
               sock.close();  
       }
       catch(SocketException e)
       {
              System.out.println("SocketException " + e);
       }
       catch(IOException e)
       {
              System.out.println("IOException " + e);
       }



The java server code is as follows:

public class Server
{
public static final int port = 1052;
public static void main( String args[])
{
Socket sock = null;
ObjectInputStream in;
String message="";
System.out.println(" Wait…… ");
try
{
ServerSocket sersock =  new ServerSocket(port);
System.out.println("Server Running  :"+sersock);
try
{
while(true)
{
sock = sersock.accept();
System.out.println("Client Connected  :"+ sock);
in = new ObjectInputStream(sock.getInputStream());
try
{
message = (String)in.readObject();
System.out.println(message);                   
}
]
catch(ClassNotFoundException classnot){
System.err.println(“Unknown data format");
}
}
sock.close();
}
catch(SocketException se)
{
System.out.println("Server Socket Exception  "+se.getMessage());
}
}
}

No comments:

Post a Comment