Android Socket Example
In this tutorial we are going to see how to use Sockets in Android Applications. In Android, sockets work exactly as they do in Java SE. In this example we are going to see how to run an Server and a Client android Application in two different emulators. This requires some special configuration regarding port forwarding, but we are going to discuss this later on.
For this tutorial, we will use the following tools in a Windows 64-bit platform:
- JDK 1.7
- Eclipse 4.2 Juno
- Android SKD 4.2
First , we have to create two Android Application Project, one for the Server and one for the Client. I’m going to display in detail, the Project creation of the Server. Of course the same apply to the Client Project creation. Then, for the Client side I’m just going to present the necessary code.
1. Create a new Android Project
Open Eclipse IDE and go to File -> New -> Project -> Android -> Android Application Project. You have to specify the Application Name, the Project Name and the Package name in the appropriate text fields and then click Next.
In the next window make sure the “Create activity” option is selected in order to create a new activity for your project, and click Next. This is optional as you can create a new activity after creating the project, but you can do it all in one step.
Select “BlankActivity” and click Next.
You will be asked to specify some information about the new activity. In the Layout Name text field you have to specify the name of the file that will contain the layout description of your app. In our case the file res/layout/main.xml
will be created. Then, click Finish.
2. Create the main layout of the Server Application
Open res/layout/main.xml
file :
And paste the following code :
main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" > </TextView> </LinearLayout>
3. Set up the Appropriate permission on AndroidManifest.xml
In order develop networking applications you have to set up the appropriate permissions in AndroidManifest.xml file :
These are the permissions:
<uses-permission android:name="android.permission.INTERNET" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" > </uses-permission>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javacodegeeks.android.androidsocketserver" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" > </uses-permission> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.javacodegeeks.android.androidsocketserver.Server" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
4. Main Server Activity
Open the source file of the main Activity and paste the following code:
Server.java:
package com.javacodegeeks.android.androidsocketserver; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.widget.TextView; public class Server extends Activity { private ServerSocket serverSocket; Handler updateConversationHandler; Thread serverThread = null; private TextView text; public static final int SERVERPORT = 6000; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); text = (TextView) findViewById(R.id.text2); updateConversationHandler = new Handler(); this.serverThread = new Thread(new ServerThread()); this.serverThread.start(); } @Override protected void onStop() { super.onStop(); try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } class ServerThread implements Runnable { public void run() { Socket socket = null; try { serverSocket = new ServerSocket(SERVERPORT); } catch (IOException e) { e.printStackTrace(); } while (!Thread.currentThread().isInterrupted()) { try { socket = serverSocket.accept(); CommunicationThread commThread = new CommunicationThread(socket); new Thread(commThread).start(); } catch (IOException e) { e.printStackTrace(); } } } } class CommunicationThread implements Runnable { private Socket clientSocket; private BufferedReader input; public CommunicationThread(Socket clientSocket) { this.clientSocket = clientSocket; try { this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream())); } catch (IOException e) { e.printStackTrace(); } } public void run() { while (!Thread.currentThread().isInterrupted()) { try { String read = input.readLine(); updateConversationHandler.post(new updateUIThread(read)); } catch (IOException e) { e.printStackTrace(); } } } } class updateUIThread implements Runnable { private String msg; public updateUIThread(String str) { this.msg = str; } @Override public void run() { text.setText(text.getText().toString()+"Client Says: "+ msg + "\n"); } } }
5. Code for the Client project
Go ahead and create a new Android Application project, as you did with the Server Application. And paste the following code snippets in the respective files:
main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <EditText android:id="@+id/EditText01" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="JavaCodeGeeks" > </EditText> <Button android:id="@+id/myButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="onClick" android:text="Send" > </Button> </LinearLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.javacodegeeks.android.androidsocketclient" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" > </uses-permission> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" > </uses-permission> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.javacodegeeks.android.androidsocketclient.Client" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Client.java:
package com.javacodegeeks.android.androidsocketclient; import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class Client extends Activity { private Socket socket; private static final int SERVERPORT = 5000; private static final String SERVER_IP = "10.0.2.2"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new Thread(new ClientThread()).start(); } public void onClick(View view) { try { EditText et = (EditText) findViewById(R.id.EditText01); String str = et.getText().toString(); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(str); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } class ClientThread implements Runnable { @Override public void run() { try { InetAddress serverAddr = InetAddress.getByName(SERVER_IP); socket = new Socket(serverAddr, SERVERPORT); } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } } }
6. Port Forwarding
In order to interconnect the programs in the two different emulators this is what happens:
- The Server program will open the port 6000 on emulator A. That means that porst 6000 is open on the ip of the emulator which is 10.0.2.15.
- Now, the client in emulator B will connect to the locahost, that is the development machine, which is aliased at 10.0.2.2 at port 5000.
- The development machine (localhost) will forward the packets to 10.0.2.15 : 6000
So in order to do that we have to do some port forwatding on the emulator. To do that, run the Server Programm in order to open the first emulator:
Now, as you can see in the Window bar, we can access the cosnole of this emulator at localhost : 5554. Press Windows Button + R, write cmd on the text box to open a comman line. In order to connect to the emulator you have to do :
telnet localhost 5554
To perform the port forwarding write:
redir add tcp:5000:6000
So now the packet will go through this direction : Emulator B -> development machine at 10.0.2.2 : 5000 -> Emulator A at 10.0.2.15 : 6000.
7. Run the client on another emulator.
In oder to run the client on another emulator, go to the Package explorer and Right Click on the Client Project. Go to Run As -> Run Configuration:
The select the Client Project for the list on the left and Click on the Target Tab. Select the second AVD and click Run:
8. Run the Application
Now that the client program is running you can send messages to the server:
Download Eclipse Project
This was an Android Socket Example. Download the Eclipse Project of this tutorial: AndroidSocketExample.zip
i get this error while trying to run the sketch: java.lang.NullPointerException: Attempt to invoke virtual method ‘java.io.OutputStream java.net.Socket.getOutputStream()’ on a null object reference
This code is extremely old and will not compile without errors. Is there any way that you could update this code?
You may follow up the latest tutorials available.
Thank you so much for this nice tutorial…problem I faced is that when I run telnet localhost window to perform port forwarding command, it doesn’t let me to type and jump immediately and back to cmd window. what is reason? what should i do? is that related to my antivirus firewall? or anything other? I will be appreciated everyone can help me to solve it. Sorry for my poor English!
Good explanation..
my code hangs at socket = serverSocket.accept(); not able to find client. why?
It is waiting for a client to connect to it. Maybe run this on the background
Its an excellent example, I ever found on Internet. Its simple and works in one go. I have tested it with multiple client. No data loss.