Saturday, June 13, 2015

Android Socket connection

Android Socket Connections is better to be started in service so that the Connections is always active in the background. This can be made as BoundServices so that Activities can interact with it easily using the Binder interface as well. 

Below two are important ingredients in making the whole thing work 

<uses-permission android:name="android.permission.INTERNET"/>

<service
   
android:name=".connectivity.SocketService"
   
android:enabled="true"
   
android:exported="true" >
</
service>

Need to add the above two in Manifest file. 

As such making a socket connection is easy, below two lines will make the connection 

InetAddress serverAddr = InetAddress.getByName(SERVERIP);

Socket socket = new Socket(serverAddr, SERVERPORT);

try
{
PrintWriter  out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
out.println(“Hello”);
out.flush();

}
catch(Exception ex)
{
}

references:

No comments:

Post a Comment