Recipe 6.8 Creating a Socket Client
The previous recipe implemented a socket server that listens at port 5000. This recipe shows how to implement a socket client that connects to it and sends it some data. In the real world, knowing how to implement a socket client will allow you to create very compelling applications. For example, you may build a cinema ticket reservation system where the socket server will listen for incoming connections from users (the socket clients) who want to reserve seats and book cinema tickets. When a user reserves a seat, all the other connected users will receive a notification informing them that a seat has been taken and is no longer available. That way, users are always looking at the updated seating plan of the cinema.
First, create the following objects:
static final String SERVER_IP = "192.168.1.13"; static final int SERVER_PORT = 5000; Handler handler = new Handler(); static Socket socket; PrintWriter printWriter;
The first two objects set the IP address and port number of the socket server (based on the example in the previous recipe). As usual, the Handler object is used to update your UI in a thread-safe manner. The Socket object is used to connect to the socket server. The PrintWriter object is a convenience method to write data to the server through an OutputStream object.
To connect ...