Module 0271: Sockets in Android

Tak Auyeung, Ph.D.

March 6, 2017

1 About this module

2 Socket concepts

A socket is a means for any number of client processes to connect to a server process. Depending on the “address” of a socket, the processes can be running on different network hosts.

Most of the time, sockets are utilized to facilitate network-based communication, but it can also be used by processes on a single computer to communicate. In general, a socket has an address that consists of the IP (Internet Protocol) address and a port number.

In socket-based communication, the process that initiates/request the connection is called a client, while the process that accepts/serve the connection is called a server. The key characteristics of socket-based communication is that many client processes can connect to the same server process.

In Android programming, it is more common that an app serves as a client than it serves as a server.

3 Java SocketChannel

The Java abstract class SocketChannel is the main mechanism to create a client end point for socket type communication. The following shows the general steps to use this class:

4 Blocking or non-Blocking?

By default, a socket channel is configured “blocking”. This means the methods connect, finishConnect, read, write can potentially block a thread from further execution until the specified operation is completed.

A potential issue with a blocking method is that it can potentially block the thread that makes the call. If the main/UI thread calls a blocking method, then all user interaction will be frozen until the call returns. Even with a timeout, this can cause perceived lag and non-responsiveness.

A blocking call can be used if a worker thread is spun off and is dedicated to handle the logic related to a socket. But then the potential issue is how this worker thread communicates and synchronizes with the other threads in a process.

This is where a state machine model can come in handy. Unlike structured code, a state machine can specify unexpected events just as easily as the “normal flow” of logic. Furthermore, a state machine helps to define external events and methods of an object.

5 Permissions

As per the Android Developer’s page, two permissions must be specified in the manifest file. The Android Studio (2.3) manifest editor is intelligent enough that you don’t have to remember exactly everything. The placement of the permissions elements must be after the <application> element,

6 Example