Click here to Skip to main content
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:


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 You need to download Eneter for.NET and Eneter for Android. More detailed technical info can be found at technical info.)


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=""
        android:versionName="1.0" >
        <uses-sdk android:minSdkVersion="7" />
        <uses-permission android:name="android.permission.INTERNET"/>
            android:label="@string/app_name" >
                android:label="@string/app_name" >
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
  3. The IP address (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 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 that is routed to (loopback) on the computer. In my example, the Android emulator uses and the .NET service is listening to

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 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. */
    public void onCreate(Bundle savedInstanceState)
        // Get UI widgets.
        myMessageTextEditText = (EditText) findViewById(;
        myResponseEditText = (EditText) findViewById(;
        mySendRequestBtn = (Button) findViewById(;
        // Subscribe to handle the button click.
        // 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()
                public void run()
                    catch (Exception err)
                        EneterTrace.error("Open connection failed.", err);
    public void onDestroy()
        // Stop listening to response messages.
    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.
        // Create TCP messaging for the communication.
        // Note: is a special alias to the loopback (
        //       on the development machine
        IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
        IDuplexOutputChannel anOutputChannel = 
        // Attach the output channel to the sender and be able to send
        // messages and receive responses.
    private void onSendRequest(View v)
        // Create the request message.
        MyRequest aRequestMsg = new MyRequest();
        aRequestMsg.Text = myMessageTextEditText.getText().toString();
        // Send the request message.
        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. Runnable()
                public void run()
    private EventHandler<TypedResponseReceivedEventArgs<MyResponse>> myOnResponseHandler
         = new EventHandler<TypedResponseReceivedEventArgs<MyResponse>>()
        public void onEvent(Object sender,
                            TypedResponseReceivedEventArgs<MyResponse> e)
            onResponseReceived(sender, e);
    private OnClickListener myOnSendRequestClickHandler = new OnClickListener()
        public void onClick(View 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 = 

            // Attach the input channel and start to listen to messages.

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

            // Detach the input channel and stop listening.
            // It releases the thread listening to messages.

        // 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:



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


About the Author

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

GeneralRe: Cannot send message from .NET to Android PinmemberawesomeDucHN1-Feb-15 22:01 
QuestionDisplaying null string on console Pinmemberprejudise2-Jan-15 5:46 
AnswerRe: Displaying null string on console PinmemberOndrej_Uzovic3-Jan-15 10:39 
GeneralRe: Displaying null string on console Pinmemberprejudise5-Jan-15 8:04 
GeneralRe: Displaying null string on console PinmemberOndrej_Uzovic5-Jan-15 9:58 
GeneralRe: Displaying null string on console Pinmemberprejudise6-Jan-15 8:03 
GeneralRe: Displaying null string on console PinmemberOndrej_Uzovic6-Jan-15 10:12 
GeneralRe: Displaying null string on console Pinmemberprejudise7-Jan-15 5:27 
GeneralRe: Displaying null string on console PinmemberOndrej_Uzovic7-Jan-15 8:44 
Questionsend message from server to android client Pinmemberfa_itb27-Dec-14 7:52 
AnswerRe: send message from server to android client PinmemberOndrej_Uzovic27-Dec-14 23:03 
GeneralRe: send message from server to android client Pinmemberfa_itb28-Dec-14 6:22 
GeneralRe: send message from server to android client PinmemberOndrej_Uzovic29-Dec-14 7:39 
GeneralRe: send message from server to android client Pinmemberfa_itb31-Dec-14 4:48 
GeneralRe: send message from server to android client PinmemberOndrej_Uzovic3-Jan-15 10:45 
QuestionNot working... Pinmemberdeveloperjm18-Dec-14 10:22 
AnswerRe: Not working... PinmemberOndrej_Uzovic19-Dec-14 2:36 
GeneralRe: Not working... Pinmemberdeveloperjm19-Dec-14 2:40 
GeneralRe: Not working... PinmemberOndrej_Uzovic19-Dec-14 2:58 
GeneralRe: Not working... Pinmemberdeveloperjm19-Dec-14 3:01 
GeneralRe: Not working... PinmemberOndrej_Uzovic19-Dec-14 3:27 
GeneralRe: Not working... Pinmemberdeveloperjm19-Dec-14 3:32 
GeneralRe: Not working... PinmemberOndrej_Uzovic19-Dec-14 3:46 
GeneralRe: Not working... Pinmemberdeveloperjm19-Dec-14 3:48 
GeneralRe: Not working... PinmemberOndrej_Uzovic19-Dec-14 4:01 
GeneralRe: Not working... Pinmemberdeveloperjm19-Dec-14 4:03 
AnswerSolution PinmemberOndrej_Uzovic21-Dec-14 6:14 
Questionconnect via wifi PinmemberMember 1124310318-Nov-14 6:48 
AnswerRe: connect via wifi PinmemberOndrej_Uzovic18-Nov-14 8:47 
Questioncommunicating between android and .NET via HTTP? [modified] PinmemberKyumin Cho6-Nov-14 22:36 
AnswerRe: communicating between android and .NET via HTTP? PinmemberOndrej_Uzovic8-Nov-14 0:40 
GeneralRe: communicating between android and .NET via HTTP? PinmemberKyumin Cho9-Nov-14 21:58 
GeneralRe: communicating between android and .NET via HTTP? PinmemberOndrej_Uzovic9-Nov-14 22:17 
QuestionProblem with running on Windows Forms PinmemberDr. Tepster1-Jun-14 8:55 
AnswerRe: Problem with running on Windows Forms PinmemberOndrej_Uzovic1-Jun-14 9:06 
Questionsocketexception was unhandled Pinmemberdeddy8330-Apr-14 18:47 
AnswerRe: socketexception was unhandled PinmemberOndrej_Uzovic30-Apr-14 21:25 
QuestionChanging IP will work Pinmembermohamedkamaleed26-Apr-14 8:08 
AnswerRe: Changing IP will work Pinmembermohamedkamaleed26-Apr-14 8:27 
QuestionNo Output on ANdroid emulator and no indication in serviceExample PinmemberMember 1075401117-Apr-14 10:10 
AnswerRe: No Output on ANdroid emulator and no indication in serviceExample PinmemberOndrej_Uzovic19-Apr-14 21:20 
GeneralRe: No Output on ANdroid emulator and no indication in serviceExample PinmemberMember 1075401119-Apr-14 21:54 
GeneralRe: No Output on ANdroid emulator and no indication in serviceExample PinmemberOndrej_Uzovic20-Apr-14 3:11 
GeneralRe: No Output on ANdroid emulator and no indication in serviceExample PinmemberMember 1075401130-Apr-14 9:36 
GeneralRe: No Output on ANdroid emulator and no indication in serviceExample PinmemberOndrej_Uzovic30-Apr-14 9:57 
Questioni want to clarify one thing which is possible on mobile Pinmemberkannanvdsr8912-Mar-14 21:29 
AnswerRe: i want to clarify one thing which is possible on mobile PinmemberOndrej_Uzovic13-Mar-14 7:16 
QuestionConnect with bluetooth PinmemberRushil Shah28-Jan-14 20:37 
AnswerRe: Connect with bluetooth PinmemberOndrej_Uzovic28-Jan-14 21:56 
QuestionError PinmemberMember 104475405-Dec-13 7:20 

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
Web04 | 2.8.150331.1 | Last Updated 20 Aug 2013
Article Copyright 2012 by Ondrej_Uzovic
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid