Java Reference
In-Depth Information
you will receive this exception: java.net.ConnectException: Connection
refused .
How It Works
Every client/server connection occurs via a socket , which is an endpoint in a commu-
nication link between two different programs. Sockets have port numbers assigned to
them, which act as an identifier for the Transmission Control Protocol/Internet Protocol
(TCP/IP) layer to use when attempting a connection. A server program that accepts re-
quests from client machines typically listens for new connections on a specified port
number. When a client wants to make a request to the server, it creates a new socket
utilizing the hostname of the server and the port on which the server is listening and at-
tempts to establish a connection with that socket. If the server accepts the socket, then
the connection is successful.
This recipe discusses the client side of the socket connection, so we will not go into
the details of what occurs on the server side at this time. However, more information
regarding the server side of a connection is covered in Recipe 21-1. The example class
in the solution to this recipe is representative of how a client-side program attempts and
establishes connections to a server-side program. In this recipe, a method named cre-
ateConnection() performs the actual connection. It accepts a server hostname and
port number, which will be used to create the socket. Within the createConnec-
tion() method, the server hostname and port number are passed to the Socket
class constructor, creating a new Socket object. Next, a PrintWriter object is
created using the Socket object's output stream, and a BufferedReader object is
created using the Socket object's input stream.
//Create socket connection
socket = new Socket(host, port);
// Obtain a handle on the socket output
out = new PrintWriter(socket.getOutputStream(),
true);
// Obtain a handle on the socket input
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
Search WWH ::




Custom Search