Android C++ TCP Server

Introduction

In this article, we will explore how to create a TCP server in Android using C++. The Android operating system provides support for native development using C++ through the Android Native Development Kit (NDK). We will build a simple TCP server application that listens for incoming connections and handles client requests. We will also discuss the necessary steps to set up the development environment and provide a code example to illustrate the implementation.

Prerequisites

To follow along with this tutorial, you will need the following:

  1. Android Studio installed on your machine.
  2. Android NDK installed.
  3. Basic knowledge of C++ programming.

Setting up the Development Environment

  1. Install Android Studio: Visit the official Android Studio website and download the latest version of Android Studio suitable for your operating system. Follow the installation instructions provided by the Android Studio installer.

  2. Install Android NDK: Open Android Studio and navigate to Preferences -> Appearance & Behavior -> System Settings -> Android SDK. Switch to the SDK Tools tab and check the box next to NDK (Side by side). Click Apply to install the NDK.

  3. Create a New Project: Open Android Studio and click on Start a new Android Studio project. Choose a project name and package name according to your preferences. Select the minimum SDK version and click Finish.

  4. Set up C++ Support: Once the project is created, open Project Structure by navigating to File -> Project Structure. In the Modules section, select your app module and switch to the Dependencies tab. Click on the + button and choose Import Module. Browse to the NDK installation directory and select the sources/cxx-stl/llvm-libc++ folder. Click OK to add the C++ support.

  5. Create a JNI Folder: Right-click on the app module in the project structure and select New -> Folder -> JNI Folder. Click OK to create the JNI folder.

  6. Add C++ Source File: Inside the JNI folder, create a new C++ source file (e.g., server.cpp) and add the following code:

#include <jni.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_myapplication_MainActivity_startServer(JNIEnv* env, jobject /* this */) {
    int serverSocket, clientSocket;
    struct sockaddr_in serverAddr, clientAddr;
    socklen_t clientAddrLen;
    char buffer[1024] = {0};
    std::string message = "Hello from the server!";
    
    // Create server socket
    if ((serverSocket = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        return env->NewStringUTF("Socket creation failed");
    }
    
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(8080);
    
    // Bind the socket to localhost:8080
    if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) {
        return env->NewStringUTF("Socket bind failed");
    }
    
    // Listen for incoming connections
    if (listen(serverSocket, 3) < 0) {
        return env->NewStringUTF("Socket listen failed");
    }
    
    // Accept incoming connection
    clientAddrLen = sizeof(clientAddr);
    if ((clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrLen)) < 0) {
        return env->NewStringUTF("Socket accept failed");
    }
    
    // Read client request
    if (read(clientSocket, buffer, 1024) < 0) {
        return env->NewStringUTF("Socket read failed");
    }
    
    // Send response to client
    send(clientSocket, message.c_str(), message.length(), 0);
    
    close(clientSocket);
    close(serverSocket);
    
    return env->NewStringUTF("Server closed");
}

Building and Running the TCP Server

To build and run the TCP server application on an Android device or emulator, follow these steps:

  1. Connect your Android device or start an emulator.

  2. Open the MainActivity.java file and add the following code to call the native method:

public class MainActivity extends AppCompatActivity {

    static {
        System.loadLibrary("tcpserver");
    }

    public native String startServer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.textView);
        textView.setText(startServer());
    }
}
  1. Run the Application: Click on the Run button in Android Studio to build and run the application on your connected device or emulator.

  2. Verify the Server: The application should display the server message in the textView. You can use a TCP client to connect to the server on localhost:8080 and send a request. The server should respond with the message "Hello from the server!".

Conclusion

In this article, we have learned how to