socket

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.

check-create-new-project

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.

check-create-new-activity

Select “BlankActivity” and click Next.

create-blanc-activity

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.

new-activity-attr

2. Create the main layout of the Server Application

Open res/layout/main.xml file :

main-xml

And paste the following code :

main.xml:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
<?xml version="1.0" encoding="utf-8"?>
    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 :

manifest

These are the permissions:

1
2
3
4
5
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
</uses-permission>

AndroidManifest.xml:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
    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:

main-activity-src

Server.java:

001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
034
035
036
037
038
039
040
041
042
043
044
045
046
047
048
049
050
051
052
053
054
055
056
057
058
059
060
061
062
063
064
065
066
067
068
069
070
071
072
073
074
075
076
077
078
079
080
081
082
083
084
085
086
087
088
089
090
091
092
093
094
095
096
097
098
099
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
<?xml version="1.0" encoding="utf-8"?>
    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:

Want to create a kick-ass Android App ?
Subscribe to our newsletter and download the Android UI Design mini-book right now!
With this book, you will delve into the fundamentals of Android UI design. You will understand user input, views and layouts, as well as adapters and fragments. Furthermore, you will learn how to add multimedia to an app and also leverage themes and styles!

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?xml version="1.0" encoding="utf-8"?>
    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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
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:

  1. 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.
  2. 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.
  3. 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:

launch-server

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 :

1
telnet localhost 5554

telnet

To perform the port forwarding write:

1
redir add tcp:5000:6000

redirection

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:

run-conficurations

The select the Client Project for the list on the left and Click on the Target Tab. Select the second AVD and click Run:

select-avd

8. Run the Application

Now that the client program is running you can send messages to the server:

emulators

Download Eclipse Project

This was an Android Socket Example. Download the Eclipse Project of this tutorial: AndroidSocketExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

8 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Artin
Artin
7 years ago

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

Gary
Gary
7 years ago

This code is extremely old and will not compile without errors. Is there any way that you could update this code?

Dev
Dev
6 years ago
Reply to  Gary

You may follow up the latest tutorials available.

Reyhane
Reyhane
6 years ago

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!

ms pearl
6 years ago

Good explanation..

Inderpreet Kaur
Inderpreet Kaur
5 years ago

my code hangs at socket = serverSocket.accept(); not able to find client. why?

Mars Pogi
Mars Pogi
4 years ago

It is waiting for a client to connect to it. Maybe run this on the background

GNoor
4 years ago

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.

Back to top button