Java Reference
In-Depth Information
The same techniques used to communicate with a finger server through a socket can be
used to connect to other popular Internet services. You could turn it into a telnet or web-
reading client with a port change in line 19 and little other modification.
Socket Servers
Server-side sockets work similarly to client sockets, with the exception of the accept()
method. A server socket listens on a TCP port for a connection from a client; when a
client connects to that port, the accept() method accepts a connection from that client.
By using both client and server sockets, you can create applications that communicate
with each other over the network.
To create a server socket and bind it to a port, create a new instance of ServerSocket
with a port number as an argument to the constructor, as in the following example:
ServerSocket servo = new ServerSocket(8888);
17
Use the accept() method to listen on that port (and to accept a connection from any
clients if one is made):
servo.accept();
After the socket connection is made, you can use input and output streams to read from
and write to the client.
To extend the behavior of the socket classes—for example, to allow network connections
to work across a firewall or a proxy—you can use the abstract class SocketImpl and the
interface SocketImplFactory to create a new transport-layer socket implementation.
This design fits with the original goal of Java's socket classes: to allow those classes to
be portable to other systems with different transport mechanisms. The problem with this
mechanism is that although it works for simple cases, it prevents you from adding other
protocols on top of TCP (for example, to implement an encryption mechanism such as
Secure Sockets Layer [SSL]) and from having multiple socket implementations per Java
runtime.
For these reasons, sockets were extended after Java 1.0, so the Socket and ServerSocket
classes are not final and extendable. You can create subclasses of these classes that use
either the default socket implementation or your own implementation. This allows much
more flexible network capabilities.
Designing a Server Application
Here's an example of a Java program that uses the Socket classes to implement a simple
network-based server application.
Search WWH ::




Custom Search