Click here to Skip to main content
11,433,220 members (56,379 online)
Click here to Skip to main content

Android: How to communicate with .NET application via TCP

, 20 Aug 2013 CPOL
Rate this:
Please Sign up or sign in to vote.
Simple example showing how to communicate between Android and .NET application.

Related articles:

Introduction

The example bellow implements a simple request-response communication between Android and .NET application. The Android application is a simple client using the .NET application as a service to calculate length of the text message.

The example bellow uses Eneter Messaging Framework making the whole communication very simple. (The framework is free and can be downloaded from http://www.eneter.net. You need to download Eneter for.NET and Eneter for Android. More detailed technical info can be found at technical info.)

340714/CommunicationBetweenAndroidandNET.png

Important: please follow this procedure (for Eclipse) to add the Eneter library into the Android project:(To add a library into the project you need to import it instead of adding it via project properties.Also ensure Java compliance level is set to 6.0. Properties -> Java Compiler -> JDK Compliance -> 1.6.)

  1. Create a new folder 'libs' in your project. (use exactly name libs)
  2. Right click on 'libs' and choose 'Import...' -> 'General/File System' -> 'Next'.
  3. Then click 'Browser' button for 'From directory' and navigate to directory with the Eneter library.
  4. Select the check box.
  5. Press 'Finish'

TCP on Android

When you implement the communication via TCP on Android, you must count with two specifics:

  1. You must set INTERNET permission for your Android application!
  2. If the permission is not set, the application is not allowed to communicate across the network. To set the INTERNET permission you must add the following line to AndroidManifest.xml.

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

    An example of AndroidManifest.xml allowing communication across the network:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="net.client"
        android:versionCode="1"
        android:versionName="1.0" >
    
        <uses-sdk android:minSdkVersion="7" />
        <uses-permission android:name="android.permission.INTERNET"/>
    
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name" >
            <activity
                android:name=".AndroidNetCommunicationClientActivity"
                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>
  3. The IP address 127.0.0.1 (loopback) cannot be set on the Android emulator to communicate with the .NET application!
  4. The emulator acts as a separate device. Therefore, the IP address 127.0.0.1 is the loopback of that device and cannot be used for the communication with other applications running on the same computer as the emulator.

    Instead of that you must use a real IP address of the computer or the emulator can use the special address 10.0.2.2 that is routed to 127.0.0.1 (loopback) on the computer. In my example, the Android emulator uses 10.0.2.2 and the .NET service is listening to 127.0.0.1.

Android Client Application

The Android client is a very simple application allowing user to put some text message and send the request to the service to get back the length of the text. When the response message is received it must be marshalled to the UI thread to display the result. Also please do not forget to set android.permission.INTERNET.

The whole implementation is very simple with using the Eneter framework:

package net.client;

import eneter.messaging.diagnostic.EneterTrace;
import eneter.messaging.endpoints.typedmessages.*;
import eneter.messaging.messagingsystems.messagingsystembase.*;
import eneter.messaging.messagingsystems.tcpmessagingsystem.TcpMessagingSystemFactory;
import eneter.net.system.EventHandler;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;

public class AndroidNetCommunicationClientActivity extends Activity
{
    // Request message type
    // The message must have the same name as declared in the service.
    // Also, if the message is the inner class, then it must be static.
    public static class MyRequest
    {
        public String Text;
    }

    // Response message type
    // The message must have the same name as declared in the service.
    // Also, if the message is the inner class, then it must be static.
    public static class MyResponse
    {
        public int Length;
    }
    
    // UI controls
    private Handler myRefresh = new Handler();
    private EditText myMessageTextEditText;
    private EditText myResponseEditText;
    private Button mySendRequestBtn;
    
    
    // Sender sending MyRequest and as a response receiving MyResponse.
    private IDuplexTypedMessageSender<MyResponse, MyRequest> mySender;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // Get UI widgets.
        myMessageTextEditText = (EditText) findViewById(R.id.messageTextEditText);
        myResponseEditText = (EditText) findViewById(R.id.messageLengthEditText);
        mySendRequestBtn = (Button) findViewById(R.id.sendRequestBtn);
        
        // Subscribe to handle the button click.
        mySendRequestBtn.setOnClickListener(myOnSendRequestClickHandler);
        
        // Open the connection in another thread.
        // Note: From Android 3.1 (Honeycomb) or higher
        //       it is not possible to open TCP connection
        //       from the main thread.
        Thread anOpenConnectionThread = new Thread(new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        openConnection();
                    }
                    catch (Exception err)
                    {
                        EneterTrace.error("Open connection failed.", err);
                    }
                }
            });
        anOpenConnectionThread.start();
    }
    
    @Override
    public void onDestroy()
    {
        // Stop listening to response messages.
        mySender.detachDuplexOutputChannel();
        
        super.onDestroy();
    } 
    
    private void openConnection() throws Exception
    {
        // Create sender sending MyRequest and as a response receiving MyResponse
        IDuplexTypedMessagesFactory aSenderFactory =
           new DuplexTypedMessagesFactory();
        mySender = aSenderFactory.createDuplexTypedMessageSender(MyResponse.class, MyRequest.class);
        
        // Subscribe to receive response messages.
        mySender.responseReceived().subscribe(myOnResponseHandler);
        
        // Create TCP messaging for the communication.
        // Note: 10.0.2.2 is a special alias to the loopback (127.0.0.1)
        //       on the development machine
        IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
        IDuplexOutputChannel anOutputChannel = 
           aMessaging.createDuplexOutputChannel("tcp://10.0.2.2:8060/");
        
        // Attach the output channel to the sender and be able to send
        // messages and receive responses.
        mySender.attachDuplexOutputChannel(anOutputChannel);
    }
    
    private void onSendRequest(View v)
    {
        // Create the request message.
        MyRequest aRequestMsg = new MyRequest();
        aRequestMsg.Text = myMessageTextEditText.getText().toString();
        
        // Send the request message.
        try
        {
            mySender.sendRequestMessage(aRequestMsg);
        }
        catch (Exception err)
        {
            EneterTrace.error("Sending the message failed.", err);
        }
    }
    
    private void onResponseReceived(Object sender, final TypedResponseReceivedEventArgs<MyResponse> e)
    {
        // Display the result - returned number of characters.
        // Note: Marshal displaying to the correct UI thread.
        myRefresh.post(new Runnable()
            {
                @Override
                public void run()
                {
                    myResponseEditText.setText(Integer.toString(e.getResponseMessage().Length));
                }
            });
    }
    
    private EventHandler<TypedResponseReceivedEventArgs<MyResponse>> myOnResponseHandler
            
         = new EventHandler<TypedResponseReceivedEventArgs<MyResponse>>()
    {
        @Override
        public void onEvent(Object sender,
                            TypedResponseReceivedEventArgs<MyResponse> e)
        {
            onResponseReceived(sender, e);
        }
    };
    
    private OnClickListener myOnSendRequestClickHandler = new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            onSendRequest(v);
        }
    };
}

.NET Service Application

The .NET service is a simple console application listening to TCP and receiving requests to calculate the length of a given text.

The implementation of the service is very simple:

using System;
using Eneter.Messaging.EndPoints.TypedMessages;
using Eneter.Messaging.MessagingSystems.MessagingSystemBase;
using Eneter.Messaging.MessagingSystems.TcpMessagingSystem;

namespace ServiceExample
{
    // Request message type
    public class MyRequest
    {
        public string Text { get; set; }
    }

    // Response message type
    public class MyResponse
    {
        public int Length { get; set; }
    }

    class Program
    {
        private static IDuplexTypedMessageReceiver<MyResponse, MyRequest> myReceiver;

        static void Main(string[] args)
        {
            // Create message receiver receiving 'MyRequest' and receiving 'MyResponse'.
            IDuplexTypedMessagesFactory aReceiverFactory = new DuplexTypedMessagesFactory();
            myReceiver = aReceiverFactory.CreateDuplexTypedMessageReceiver<MyResponse, MyRequest>();

            // Subscribe to handle messages.
            myReceiver.MessageReceived += OnMessageReceived;

            // Create TCP messaging.
            IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
            IDuplexInputChannel anInputChannel = 
               aMessaging.CreateDuplexInputChannel("tcp://127.0.0.1:8060/");

            // Attach the input channel and start to listen to messages.
            myReceiver.AttachDuplexInputChannel(anInputChannel);

            Console.WriteLine("The service is running. To stop press enter.");
            Console.ReadLine();

            // Detach the input channel and stop listening.
            // It releases the thread listening to messages.
            myReceiver.DetachDuplexInputChannel();
        }

        // It is called when a message is received.
        private static void OnMessageReceived(object sender, 
              TypedRequestReceivedEventArgs<MyRequest> e)
        {
            Console.WriteLine("Received: " + e.RequestMessage.Text);

            // Create the response message.
            MyResponse aResponse = new MyResponse();
            aResponse.Length = e.RequestMessage.Text.Length;

            // Send the response message back to the client.
            myReceiver.SendResponseMessage(e.ResponseReceiverId, aResponse);
        }
    }
}

And here are applications communicating together:

340714/AndroidCommunicatesWithNetUI.jpg

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ondrej_Uzovic
Architect
Slovakia Slovakia
My programming path started in 1987 when I got my first computer Sharp MZ-800.
It came with 8 bit CPU Z80, 64Kb RAM and the tape recorder. It was a great machine. I think I still have it somewhere.
I was fascinated and I started to write first programs. Eventually I became developer and software architect. I like innovations and clean nice solutions.

Comments and Discussions

 
QuestionI think same thing can be done using WCF?? Pin
Mohammed Hameed11-Jul-13 2:45
professionalMohammed Hameed11-Jul-13 2:45 
AnswerRe: I think same thing can be done using WCF?? Pin
Ondrej_Uzovic31-Aug-13 2:34
memberOndrej_Uzovic31-Aug-13 2:34 
QuestionIf it support binary streams? Pin
alin.zhang19-Jun-13 20:42
memberalin.zhang19-Jun-13 20:42 
AnswerRe: If it support binary streams? Pin
Ondrej_Uzovic20-Jun-13 10:04
memberOndrej_Uzovic20-Jun-13 10:04 
GeneralRe: If it support binary streams? Pin
iJam_j28-Nov-13 0:42
memberiJam_j28-Nov-13 0:42 
GeneralRe: If it support binary streams? Pin
Ondrej_Uzovic28-Nov-13 8:33
memberOndrej_Uzovic28-Nov-13 8:33 
QuestionAdding security Pin
Cory Shirts7-Jun-13 10:43
memberCory Shirts7-Jun-13 10:43 
AnswerRe: Adding security Pin
Ondrej_Uzovic9-Jun-13 10:38
memberOndrej_Uzovic9-Jun-13 10:38 
GeneralRe: Adding security Pin
Cory Shirts10-Jun-13 7:14
memberCory Shirts10-Jun-13 7:14 
GeneralThank You Pin
Bobbydoo816-May-13 4:34
memberBobbydoo816-May-13 4:34 
QuestionHow to send data from android application to .net web site Pin
Member 986794023-Mar-13 22:05
memberMember 986794023-Mar-13 22:05 
AnswerRe: How to send data from android application to .net web site Pin
Ondrej_Uzovic24-Mar-13 1:09
memberOndrej_Uzovic24-Mar-13 1:09 
GeneralVery helpful Pin
| B | A | N | D | I |16-Feb-13 1:03
member| B | A | N | D | I |16-Feb-13 1:03 
QuestionUsing it over the internet instead of locally? Pin
Master_T7-Jan-13 5:55
memberMaster_T7-Jan-13 5:55 
Hi

I built an app using Eneter (the server is written in java) and it works using the local IPs
The code it's the same as in your example, only I used the real "public" IP address instead of the local one.

But when I do that the library stops working, it fails to listen to the channel:

java.net.BindException: Cannot assign requested address: JVM_Bind
	at java.net.DualStackPlainSocketImpl.bind0(Native Method)
	at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
	at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
	at java.net.PlainSocketImpl.bind(Unknown Source)
	at java.net.ServerSocket.bind(Unknown Source)
	at eneter.messaging.messagingsystems.tcpmessagingsystem.NoneSecurityServerFactory.createServerSocket(NoneSecurityServerFactory.java:32)
	at eneter.messaging.messagingsystems.tcpmessagingsystem.internal.TcpListenerProvider.startListening(TcpListenerProvider.java:121)
	at eneter.messaging.messagingsystems.tcpmessagingsystem.TcpInputChannelBase.startListening(TcpInputChannelBase.java:74)
	at eneter.messaging.infrastructure.attachable.internal.AttachableDuplexInputChannelBase.attachDuplexInputChannel(AttachableDuplexInputChannelBase.java:38)
	at DARCOServer.Messaging.MessagingManager.OpenConnection(MessagingManager.java:74)
	at DARCOServer.MainClass.main(MainClass.java:36)

Any ideas?
AnswerRe: Using it over the internet instead of locally? Pin
Ondrej_Uzovic20-Jan-13 23:31
memberOndrej_Uzovic20-Jan-13 23:31 
AnswerRe: Using it over the internet instead of locally? Pin
Renaud Gauthier12-Mar-13 7:09
memberRenaud Gauthier12-Mar-13 7:09 
GeneralMy vote of 5 Pin
Phat (Phillip) H. VU3-Jan-13 19:55
memberPhat (Phillip) H. VU3-Jan-13 19:55 
GeneralMy vote of 5 Pin
Member 952628628-Dec-12 8:40
memberMember 952628628-Dec-12 8:40 
QuestionI use simulator,but does not work. Pin
Member 952628628-Dec-12 8:39
memberMember 952628628-Dec-12 8:39 
AnswerRe: I use simulator,but does not work. Pin
Ondrej_Uzovic1-Jan-13 0:19
memberOndrej_Uzovic1-Jan-13 0:19 
GeneralMy vote of 5 Pin
Serguei_Ko13-Dec-12 23:10
memberSerguei_Ko13-Dec-12 23:10 
GeneralMy vote of 5 Pin
christoph brändle12-Dec-12 0:21
memberchristoph brändle12-Dec-12 0:21 
GeneralMy vote of 5 Pin
URVISHSUTHAR9-Dec-12 21:29
memberURVISHSUTHAR9-Dec-12 21:29 
QuestionLaunch in Android SDK Pin
BOWLINGBALL4-Dec-12 12:44
memberBOWLINGBALL4-Dec-12 12:44 
AnswerRe: Launch in Android SDK Pin
Ondrej_Uzovic5-Dec-12 9:36
memberOndrej_Uzovic5-Dec-12 9:36 
GeneralRe: Launch in Android SDK Pin
BOWLINGBALL7-Dec-12 8:27
memberBOWLINGBALL7-Dec-12 8:27 
GeneralRe: Launch in Android SDK Pin
Ondrej_Uzovic8-Dec-12 9:54
memberOndrej_Uzovic8-Dec-12 9:54 
GeneralRe: Launch in Android SDK Pin
BOWLINGBALL7-Dec-12 12:22
memberBOWLINGBALL7-Dec-12 12:22 
GeneralRe: Launch in Android SDK Pin
Ondrej_Uzovic8-Dec-12 10:03
memberOndrej_Uzovic8-Dec-12 10:03 
GeneralRe: Launch in Android SDK Pin
BOWLINGBALL10-Dec-12 12:44
memberBOWLINGBALL10-Dec-12 12:44 
GeneralRe: Launch in Android SDK Pin
Ondrej_Uzovic11-Dec-12 9:23
memberOndrej_Uzovic11-Dec-12 9:23 
GeneralRe: Launch in Android SDK Pin
BOWLINGBALL11-Jan-13 12:27
memberBOWLINGBALL11-Jan-13 12:27 
GeneralRe: Launch in Android SDK Pin
Ondrej_Uzovic11-Jan-13 21:21
memberOndrej_Uzovic11-Jan-13 21:21 
GeneralMy vote of 5 Pin
Manar Ezzadeen17-Nov-12 10:19
memberManar Ezzadeen17-Nov-12 10:19 
QuestionHelp needed !! [modified] Pin
seanmir13-Nov-12 8:37
memberseanmir13-Nov-12 8:37 
AnswerRe: Help needed !! Pin
Ondrej_Uzovic13-Nov-12 22:41
memberOndrej_Uzovic13-Nov-12 22:41 
GeneralRe: Help needed !! Pin
seanmir14-Nov-12 0:59
memberseanmir14-Nov-12 0:59 
GeneralRe: Help needed !! Pin
Ondrej_Uzovic14-Nov-12 23:03
memberOndrej_Uzovic14-Nov-12 23:03 
GeneralThat's what i am looking for. Pin
wreid17-Oct-12 0:52
memberwreid17-Oct-12 0:52 
GeneralMy vote of 5 Pin
Kanasz Robert23-Sep-12 4:17
mvpKanasz Robert23-Sep-12 4:17 
QuestionIn 20 minutes to success Pin
Member 87928464-Aug-12 12:54
memberMember 87928464-Aug-12 12:54 
AnswerRe: In 20 minutes to success Pin
Ondrej_Uzovic5-Aug-12 3:05
memberOndrej_Uzovic5-Aug-12 3:05 
QuestionError: Pin
IBR_BAR29-Apr-12 13:54
memberIBR_BAR29-Apr-12 13:54 
BugRe: Error: Pin
mitnick90230-Apr-12 7:21
membermitnick90230-Apr-12 7:21 
GeneralRe: Error: Pin
Ondrej_Uzovic30-Apr-12 8:34
memberOndrej_Uzovic30-Apr-12 8:34 
GeneralRe: Error: Pin
mitnick9022-May-12 13:22
membermitnick9022-May-12 13:22 
AnswerRe: Error: Pin
Ondrej_Uzovic30-Apr-12 8:39
memberOndrej_Uzovic30-Apr-12 8:39 
AnswerRe: Error: Pin
Member 896983911-Jul-12 7:47
memberMember 896983911-Jul-12 7:47 
GeneralRe: Error: Pin
Ondrej_Uzovic11-Jul-12 9:53
memberOndrej_Uzovic11-Jul-12 9:53 
Questionexample Project SimpleTcp Pin
roberto.reff12-Apr-12 6:39
memberroberto.reff12-Apr-12 6:39 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150428.2 | Last Updated 20 Aug 2013
Article Copyright 2012 by Ondrej_Uzovic
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid