Chapter 11. Sockets for Servers

The last chapter discussed sockets from the standpoint of clients: programs that open a socket to a server that’s listening for connections. However, client sockets themselves aren’t enough; clients aren’t much use unless they can talk to a server, and if you think about it, the sockets we discussed in the last chapter aren’t sufficient for writing servers. To create a Socket, you need to know the Internet host to which you want to connect. When you’re writing a server, you don’t know in advance who will contact you, and even if you did, you wouldn’t know when that host wanted to contact you. In other words, servers are like receptionists who sit by the phone and wait for incoming calls. They don’t know who will call or when, only that when the phone rings, they have to pick it up and talk to whoever is there. We can’t program that behavior with the Socket class alone. Granted, there’s no reason that clients written in Java have to talk to Java servers—in fact, a client doesn’t care what language the server was written in or what platform it runs on. However, if Java didn’t let us write servers, there would be a glaring hole in its capabilities.

Fortunately, there’s no such hole. Java provides a ServerSocket class to allow programmers to write servers. Basically, a server socket’s job is to sit by the phone and wait for incoming calls. More technically, a ServerSocket runs on the server and listens for incoming TCP connections. Each ServerSocket ...

Get Java Network Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.