Click here to Skip to main content
12,943,913 members (55,198 online)
Click here to Skip to main content
Add your own
alternative version

Stats

291.6K views
9.6K downloads
262 bookmarked
Posted 5 Mar 2012

Android: How to communicate with .NET application via TCP

, 5 Mar 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Simple example showing how to communicate between Android and .NET application.
This is an old version of the currently published article.


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 for non-commercial use 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


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!

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



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>


2. The IP address 127.0.0.1 (loopback) cannot be used for communication between the Android emulator and the .NET application!

The emulator acts as a separate device. Therefore, the IP address 127.0.0.1 (loopback) 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. It is the reason why the example uses 172.16.0.6 => Do not forget to use your own IP address to make the example running.


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 and set the valid IP address - since 127.0.0.1 cannot be used - see the explanation above.



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);
        
        try
        {
            openConnection();
        }
        catch (Exception err)
        {
            EneterTrace.error("Open connection failed.", err);
        }
    }
    
    @Override
    public void onDestroy()
    {
        // Stop listening to response messages.
        mySender.detachDuplexOutputChannel();
    } 
    
    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.
        IMessagingSystemFactory aMessaging = new TcpMessagingSystemFactory();
        IDuplexOutputChannel anOutputChannel = 
           aMessaging.createDuplexOutputChannel("tcp://172.16.0.6: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.
Since the IP address 127.0.0.1 (loopback) cannot be used, do not forget to set a real IP address the Android emulator (or real device) can use to reach the service application.



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

You may also be interested in...

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.
 
GeneralMy vote of 5 Pin
GregoryW6-Mar-12 2:37
memberGregoryW6-Mar-12 2:37 
GeneralMy vote of 5 Pin
Patrick Harris5-Mar-12 16:35
memberPatrick Harris5-Mar-12 16:35 

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

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


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
Question.NET as client Pin
Member 1305567613-Mar-17 1:09
memberMember 1305567613-Mar-17 1:09 
AnswerRe: .NET as client Pin
Ondrej_Uzovic14-Apr-17 6:50
memberOndrej_Uzovic14-Apr-17 6:50 
GeneralRe: .NET as client Pin
Member 1305567621-Apr-17 1:50
memberMember 1305567621-Apr-17 1:50 
QuestionMessage Removed Pin
Refaghatjoo3-Dec-16 6:49
memberRefaghatjoo3-Dec-16 6:49 
QuestionCommunication Problem Pin
Refaghatjoo17-Nov-16 15:14
memberRefaghatjoo17-Nov-16 15:14 
AnswerRe: Communication Problem Pin
Ondrej_Uzovic17-Nov-16 21:40
memberOndrej_Uzovic17-Nov-16 21:40 
GeneralRe: Communication Problem Pin
Refaghatjoo18-Nov-16 3:32
memberRefaghatjoo18-Nov-16 3:32 
GeneralRe: Communication Problem Pin
Ondrej_Uzovic18-Nov-16 4:27
memberOndrej_Uzovic18-Nov-16 4:27 
GeneralRe: Communication Problem Pin
Refaghatjoo18-Nov-16 17:22
memberRefaghatjoo18-Nov-16 17:22 
GeneralRe: Communication Problem Pin
Ondrej_Uzovic19-Nov-16 2:29
memberOndrej_Uzovic19-Nov-16 2:29 
GeneralRe: Communication Problem Pin
Refaghatjoo24-Nov-16 5:35
memberRefaghatjoo24-Nov-16 5:35 
GeneralRe: Communication Problem Pin
Refaghatjoo1-Dec-16 15:59
memberRefaghatjoo1-Dec-16 15:59 
QuestionMessage Removed Pin
Quangg Hà6-Sep-16 23:55
memberQuangg Hà6-Sep-16 23:55 
Questionsend an image rather than a text ? Pin
om.albaraa24-Jun-16 13:26
memberom.albaraa24-Jun-16 13:26 
AnswerRe: send an image rather than a text ? Pin
Ondrej_Uzovic24-Jun-16 23:26
memberOndrej_Uzovic24-Jun-16 23:26 
GeneralRe: send an image rather than a text ? Pin
om.albaraa25-Jun-16 17:38
memberom.albaraa25-Jun-16 17:38 
GeneralRe: send an image rather than a text ? Pin
Ondrej_Uzovic25-Jun-16 21:04
memberOndrej_Uzovic25-Jun-16 21:04 
QuestionCommunication problem Pin
moimemedede20-Jun-16 1:07
membermoimemedede20-Jun-16 1:07 
AnswerRe: Communication problem Pin
Ondrej_Uzovic20-Jun-16 2:06
memberOndrej_Uzovic20-Jun-16 2:06 
GeneralRe: Communication problem Pin
moimemedede20-Jun-16 8:40
membermoimemedede20-Jun-16 8:40 
GeneralRe: Communication problem Pin
Ondrej_Uzovic21-Jun-16 20:36
memberOndrej_Uzovic21-Jun-16 20:36 
QuestionNull Exception Pin
Mike885519-Apr-16 20:47
memberMike885519-Apr-16 20:47 
AnswerRe: Null Exception Pin
Ondrej_Uzovic19-Apr-16 22:52
memberOndrej_Uzovic19-Apr-16 22:52 
GeneralRe: Null Exception Pin
Mike885520-Apr-16 3:45
memberMike885520-Apr-16 3:45 
GeneralRe: Null Exception Pin
xocode15-Aug-16 1:42
memberxocode15-Aug-16 1:42 

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

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

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170518.1 | Last Updated 5 Mar 2012
Article Copyright 2012 by Ondrej_Uzovic
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid