Android Socket Programming — TCP Server Example

Perihan Mirkelam
3 min readJan 3, 2021
Image by phatplus on flaticon.com

What is Socket Programming?

Socket programming is a way for devices to communicate over a network. Two sockets communicate, one on the client-side and one on the server-side.

A socket’s address consists of an IP and a port. The server application starts to listen to clients over the defined port. The client establishes a connection over the IP of the server and the port it opens. The communication can then continue bidirectionally.

An example server socket address: 192.168.1.10:9876

Socket programming is a frequently preferred method in IoT applications. Devices communicate on the network. It is an environment-independent method as the communication is provided over the TCP / IP protocol. Thus, a PLC can communicate with an Android device as well as an Arduino can communicate with a Linux machine.

Let’s look at a scenario using the TCP protocol where the Android application is the server:

  • Add permissions to Manifest
  • We will run our server in an Android Service.
  • Let’s create a foreground service because the application is running in the background for a long time. We do not want our service to be killed by Android OS.
  • Add Foreground service notification settings.
  • Since sending/reading data with the socket at Android is a network operation (I/O operation), it should not be run in the UI/Main thread.
  • Create a new thread (or use coroutines with Dispatchers.IO) for socket operations when the Foreground service is started. Because, we are still working on the main thread, even though it is a service.
  • Define the socket with the port number to start listening to clients.
  • Create a new thread for each new client connection to handle them simultaneously.
  • Listen to the message from a connected client and respond to them with a “Hello Client” message.
  • Declare the service in Manifest
  • Start the service from the launcher activity

By running this application on your Android device, you can establish a client connection with your computer on the same network. Connect and send a message from the shell (Linux, macOS, Windows) with the help of the Netcat tool:

echo "Halo Server!" | nc 192.168.1.10 9876

or

nc 192.168.1.10 9876 < something_to_say.txt

We have created the TCP server application in its simplest form. The client application can be created quite similarly.

To simplify the example, no user interaction is included. With GUI enhancements, the port and message to be sent could be changed.
You can access the source codes of client and server applications designed to communicate with each other below.

--

--