Recipe 6.7 Creating a Socket Server
A socket is an endpoint of an application participating in a two-way communication across the network. A socket is comprised of an IP address and a port number. Using sockets, applications can efficiently transfer data across the network. In this recipe, you will learn how to create a socket server that listens for incoming connections. Then, Recipe 6.8 shows you how to develop a socket client that connects to the server.
To create a socket server, first declare four objects as follows:
static String SERVER_IP; static final int SERVER_PORT = 5000; Handler handler = new Handler(); ServerSocket serverSocket;
The first object holds the IP address of the device, which will act as a socket server. The second object holds the port number on which the server is listening. In theory, you can use any port number from 0 to 65,535, but in the real world port numbers from 0 to 1,023 are typically reserved for running privileged server processes. Hence, your port number can be from 1,024 to 65,535, as long as it does not conflict with another application running on the device with the same port number that you have chosen.
The Handler object is used to update your UI. Typically, you need to do this if you are currently executing on a separate thread other than the UI and you need to update the UI. This ...