How to connect to an Android server socket in the emulator

22 December 2012
By Gonçalo Marques
In this tutorial you will learn how to connect to a server socket that is running in the Android emulator.

Introduction

This tutorial will not focus on how to create Android activities or applications from scratch. It will assume that you already have a basic understanding about Android application development and will jump straight into the server sockets running in the emulator example.

Used software:

  1. Ubuntu 12.04
  2. Eclipse Juno
  3. Android SDK 21.0.0

A simple Android server

Let's create a very simple activity that opens a server socket and listens for incoming connections:

A simple Android activity
package com.byteslounge.android.server;

import pt.webprods.android.file.manager.R;
import android.app.Activity;
import android.os.Bundle;

public class HomeActivity extends Activity {
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_activity);
    new ServerThread().start();
  }
  
}

This activity is basically launching a separate thread that will listen for incoming connections.

The thread class looks like the following:

ServerThread class
package com.byteslounge.android.server;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;

public class ServerThread extends Thread {

  private ServerSocket serverSocket;
  private Socket clientSocket;
  private PrintWriter out;
  private BufferedReader in;
  
  public void run(){
    
    try{
      // Open a server socket listening on port 8080
      InetAddress addr = InetAddress.getByName(getLocalIpAddress());
      serverSocket = new ServerSocket(8080, 0, addr);
      clientSocket = serverSocket.accept();
      
      // Client established connection.
      // Create input and output streams
      in = new BufferedReader(
             new InputStreamReader(clientSocket.getInputStream()));
      out = new PrintWriter(clientSocket.getOutputStream(), true);
      
      // Read received data and echo it back
      String input = in.readLine();
      out.println("received: " + input);
      
      // Perform cleanup
      in.close();
      out.close();

    } catch(Exception e) {
      // Omitting exception handling for clarity
    }
  }
  
  private String getLocalIpAddress() throws Exception {
    String resultIpv6 = "";
    String resultIpv4 = "";
      
      for (Enumeration en = NetworkInterface.getNetworkInterfaces(); 
        en.hasMoreElements();) {

        NetworkInterface intf = en.nextElement();
        for (Enumeration enumIpAddr = intf.getInetAddresses(); 
            enumIpAddr.hasMoreElements();) {

            InetAddress inetAddress = enumIpAddr.nextElement();
            if(!inetAddress.isLoopbackAddress()){
              if (inetAddress instanceof Inet4Address) {
                resultIpv4 = inetAddress.getHostAddress().toString();
                } else if (inetAddress instanceof Inet6Address) {
                  resultIpv6 = inetAddress.getHostAddress().toString();
                }
            }
        }
    }
    return ((resultIpv4.length() > 0) ? resultIpv4 : resultIpv6);
  }
}


Note that you should not launch threads like this in your real application. This is just for the simplicity of this example. You should use an asynchronous task or a background service instead.

Launching and testing

By now you should launch your application in the emulator. When it shows us up note the port in the upper left corner:

Android emulator listening port
Android emulator listening port

Connect to the emulator issuing the following telnet command using the emulator port:

telnet localhost 5554

Now you have an open session connected to the emulator. Remember we created the server socket listening on port 8080? Let's add a redirection rule that redirects connections from an arbitrary port - let's say 5050 - to our server socket port. Issue the following command:

redir add tcp:5050:8080

Now you can type exit to leave the emulator session. If everything went OK it should look like the following:

Adding port redirection rule to the emulator
Android emulator port redirection rule

We are now ready to connect to our server socket and test it. Now issue the following command:

telnet localhost 5050

A connection to your Android server socket will be established. Now when you enter some random message into the console you will receive the echo from the server:

Sending and receiving
Android emulator sending and receiving data

That's it. You can now test your Android server applications in the emulator without needing a real device.

Related Articles

Comments

About the author
Gonçalo Marques is a Software Engineer with several years of experience in software development and architecture definition. During this period his main focus was delivering software solutions in banking, telecommunications and governmental areas. He created the Bytes Lounge website with one ultimate goal: share his knowledge with the software development community. His main area of expertise is Java and open source.

GitHub profile: https://github.com/gonmarques

He is also the author of the WiFi File Browser Android application: