Chapter 17. Server-Side Java: Sockets
Introduction
Sockets form the underpinnings of almost all networking protocols. JDBC,
RMI, CORBA, EJB, and the non-Java RPC (Remote Procedure Call) and NFS
(Network File System) are all implemented by connecting various types of
sockets together. Socket connections can be implemented in many
languages, not just Java: C, C++, Perl, and Python are also popular, and
many others are possible. A client or server written in any one of these
languages can communicate with its opposite written in any of the other
languages. Therefore, it’s worth taking a quick look at how the ServerSocket
behaves, even if you wind up
utilizing the higher-level services such as RMI, JDBC, CORBA, or
EJB.
The discussion looks first at the ServerSocket
itself, then at writing data over
a socket in various ways. Finally, we show a complete implementation of
a usable network server written in Java: the chat server from the client
in the previous chapter.
17.1. Opening a Server for Business
Problem
You need to write a socket-based server.
Solution
Create a ServerSocket
for the given port number.
Discussion
The ServerSocket
represents
the “other end” of a connection, the server that waits patiently for
clients to come along and connect to it. You construct a ServerSocket
with just the port
number.[1] Since it doesn’t need to connect to another host, it
doesn’t need a particular host’s address as the client socket
constructor does.
Assuming the ServerSocket
constructor doesn’t throw ...
Get Java Cookbook, 2nd 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.