Android Socket Example

http://examples.javacodegeeks.com/android/core/socket-core/android-socket-example/


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 <?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03     android:layout_width="fill_parent"
04     android:layout_height="fill_parent"
05     android:orientation="vertical" >
06  
07     <TextView
08         android:id="@+id/text2"
09         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:text="" >
12     </TextView>
13  
14 </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 <uses-permission android:name="android.permission.INTERNET" >
2 </uses-permission>
3  
4 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
5 </uses-permission>

AndroidManifest.xml:

01 <?xml version="1.0" encoding="utf-8"?>
02 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
03     package="com.javacodegeeks.android.androidsocketserver"
04     android:versionCode="1"
05     android:versionName="1.0" >
06  
07     <uses-sdk
08         android:minSdkVersion="8"
09         android:targetSdkVersion="17" />
10  
11     <uses-permission android:name="android.permission.INTERNET" >
12     </uses-permission>
13  
14     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
15     </uses-permission>
16  
17     <application
18         android:allowBackup="true"
19         android:icon="@drawable/ic_launcher"
20         android:label="@string/app_name"
21         android:theme="@style/AppTheme" >
22         <activity
23             android:name="com.javacodegeeks.android.androidsocketserver.Server"
24             android:label="@string/app_name" >
25             <intent-filter>
26                 <action android:name="android.intent.action.MAIN" />
27  
28                 <category android:name="android.intent.category.LAUNCHER" />
29             </intent-filter>
30         </activity>
31     </application>
32  
33 </manifest>

4. Main Server Activity

Open the source file of the main Activity and paste the following code:

main-activity-src

Server.java:

001 package com.javacodegeeks.android.androidsocketserver;
002  
003 import java.io.BufferedReader;
004 import java.io.IOException;
005 import java.io.InputStreamReader;
006 import java.net.ServerSocket;
007 import java.net.Socket;
008  
009 import android.app.Activity;
010 import android.os.Bundle;
011 import android.os.Handler;
012 import android.widget.TextView;
013  
014 public class Server extends Activity {
015  
016     private ServerSocket serverSocket;
017  
018     Handler updateConversationHandler;
019  
020     Thread serverThread = null;
021  
022     private TextView text;
023  
024     public static final int SERVERPORT = 6000;
025  
026     @Override
027     public void onCreate(Bundle savedInstanceState) {
028  
029         super.onCreate(savedInstanceState);
030         setContentView(R.layout.main);
031  
032         text = (TextView) findViewById(R.id.text2);
033  
034         updateConversationHandler = new Handler();
035  
036         this.serverThread = new Thread(new ServerThread());
037         this.serverThread.start();
038  
039     }
040  
041     @Override
042     protected void onStop() {
043         super.onStop();
044         try {
045             serverSocket.close();
046         catch (IOException e) {
047             e.printStackTrace();
048         }
049     }
050  
051     class ServerThread implements Runnable {
052  
053         public void run() {
054             Socket socket = null;
055             try {
056                 serverSocket = new ServerSocket(SERVERPORT);
057             catch (IOException e) {
058                 e.printStackTrace();
059             }
060             while (!Thread.currentThread().isInterrupted()) {
061  
062                 try {
063  
064                     socket = serverSocket.accept();
065  
066                     CommunicationThread commThread = new CommunicationThread(socket);
067                     new Thread(commThread).start();
068  
069                 catch (IOException e) {
070                     e.printStackTrace();
071                 }
072             }
073         }
074     }
075  
076     class CommunicationThread implements Runnable {
077  
078         private Socket clientSocket;
079  
080         private BufferedReader input;
081  
082         public CommunicationThread(Socket clientSocket) {
083  
084             this.clientSocket = clientSocket;
085  
086             try {
087  
088                 this.input = new BufferedReader(newInputStreamReader(this.clientSocket.getInputStream()));
089  
090             catch (IOException e) {
091                 e.printStackTrace();
092             }
093         }
094  
095         public void run() {
096  
097             while (!Thread.currentThread().isInterrupted()) {
098  
099                 try {
100  
101                     String read = input.readLine();
102  
103                     updateConversationHandler.post(new updateUIThread(read));
104  
105                 catch (IOException e) {
106                     e.printStackTrace();
107                 }
108             }
109         }
110  
111     }
112  
113     class updateUIThread implements Runnable {
114         private String msg;
115  
116         public updateUIThread(String str) {
117             this.msg = str;
118         }
119  
120         @Override
121         public void run() {
122             text.setText(text.getText().toString()+"Client Says: "+ msg + "\n");
123         }
124     }
125 }

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 <?xml version="1.0" encoding="utf-8"?>
02 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
03     android:layout_width="fill_parent"
04     android:layout_height="fill_parent"
05     android:orientation="vertical" >
06  
07     <EditText
08         android:id="@+id/EditText01"
09         android:layout_width="fill_parent"
10         android:layout_height="wrap_content"
11         android:text="JavaCodeGeeks" >
12     </EditText>
13  
14     <Button
15         android:id="@+id/myButton"
16         android:layout_width="wrap_content"
17         android:layout_height="wrap_content"
18         android:onClick="onClick"
19         android:text="Send" >
20     </Button>
21  
22 </LinearLayout>

AndroidManifest.xml:

01 <?xml version="1.0" encoding="utf-8"?>
02 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
03     package="com.javacodegeeks.android.androidsocketclient"
04     android:versionCode="1"
05     android:versionName="1.0" >
06  
07     <uses-sdk
08         android:minSdkVersion="8"
09         android:targetSdkVersion="17" />
10  
11     <uses-permission android:name="android.permission.INTERNET" >
12     </uses-permission>
13  
14     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" >
15     </uses-permission>
16  
17     <application
18         android:allowBackup="true"
19         android:icon="@drawable/ic_launcher"
20         android:label="@string/app_name"
21         android:theme="@style/AppTheme" >
22         <activity
23             android:name="com.javacodegeeks.android.androidsocketclient.Client"
24             android:label="@string/app_name" >
25             <intent-filter>
26                 <action android:name="android.intent.action.MAIN" />
27  
28                 <category android:name="android.intent.category.LAUNCHER" />
29             </intent-filter>
30         </activity>
31     </application>
32  
33 </manifest>

Client.java:

01 package com.javacodegeeks.android.androidsocketclient;
02  
03 import java.io.BufferedWriter;
04 import java.io.IOException;
05 import java.io.OutputStreamWriter;
06 import java.io.PrintWriter;
07 import java.net.InetAddress;
08 import java.net.Socket;
09 import java.net.UnknownHostException;
10  
11 import android.app.Activity;
12 import android.os.Bundle;
13 import android.view.View;
14 import android.widget.EditText;
15  
16 public class Client extends Activity {
17  
18     private Socket socket;
19  
20     private static final int SERVERPORT = 5000;
21     private static final String SERVER_IP = "10.0.2.2";
22  
23     @Override
24     public void onCreate(Bundle savedInstanceState) {
25         super.onCreate(savedInstanceState);
26         setContentView(R.layout.main);     
27  
28         new Thread(new ClientThread()).start();
29     }
30  
31     public void onClick(View view) {
32         try {
33             EditText et = (EditText) findViewById(R.id.EditText01);
34             String str = et.getText().toString();
35             PrintWriter out = new PrintWriter(new BufferedWriter(
36                     new OutputStreamWriter(socket.getOutputStream())),
37                     true);
38             out.println(str);
39         catch (UnknownHostException e) {
40             e.printStackTrace();
41         catch (IOException e) {
42             e.printStackTrace();
43         catch (Exception e) {
44             e.printStackTrace();
45         }
46     }
47  
48     class ClientThread implements Runnable {
49  
50         @Override
51         public void run() {
52  
53             try {
54                 InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
55  
56                 socket = new Socket(serverAddr, SERVERPORT);
57  
58             catch (UnknownHostException e1) {
59                 e1.printStackTrace();
60             catch (IOException e1) {
61                 e1.printStackTrace();
62             }
63  
64         }
65  
66     }
67 }

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值