Chapter 2 Networking in Java
Chapter 2 Networking in Java
CHAPTER TWO
NETWORKING IN JAVA
Socket Programming
Computers running on the Internet communicate with each other using either
the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).
When you write Java programs that communicate over the network, you are
programming at the application layer.
Typically, you don't need to concern yourself with the TCP and UDP layers.
Instead, you can use the classes in the java.net package.
These classes provide system-independent network communication.
However, to decide which Java classes your programs should use, you do
need to understand how TCP and UDP differ.
1. Sockets…
3
Ports
Generally speaking, a computer has a single physical connection to the
network.
All data destined for a particular computer arrives through that connection.
However, the data may be intended for different applications/servers
running on the computer.
So how does the computer know to which application to forward the data?
Through the use of ports.
Data transmitted over the Internet is accompanied by addressing
information that identifies the computer and the port for which it is destined.
1. Sockets…
5
The InetAddress class has several other methods, which can be used
on the objects returned by the methods discussed above.
Here are some of the more commonly used methods:
Method Description
Returns a byte array that represents the object’s IP address
byte[ ] getAddress()
in network byte order.
Returns a string that represents the IP address associated
String getHostAddress()
with the InetAddress object.
Returns a string that represents the host name associated
String getHostName()
with the InetAddress object.
InetAddress…
10
Java’s URL class has several constructors and each can throw a
MalformedURLException.
One commonly used form specifies the URL with a string that is identical to
what you see displayed in a browser:
URL(String url) – creates a URL object from the String representation. It
throws MalformedURLException if no protocol is specified, or unknown
protocol is used, or url is null.
URL(String protocol, String host, String file) – creates a URL from the
specified protocol name, host name, and file name. The default port for
the specified protocol is used. It throws MalformedURLException.
URL(String protocol, String host, int port, String file ) – creates a URL
object from the specified protocol, host, port number, and file. host can
be expressed as a host name or a literal IP address. Throws
MalformedURLException.
URL(URL urlObj, String url) - Creates a URL by parsing the given spec
within a specified context. It throws MalformedURLException.
URL…
14
String getFile() returns the file name of this URL, or an empty string if it does not exist
URLConnection opens a connection to the given URL and return URLConnection object if
openConnection() successful
URL…
15
Protocol: http
Port: -1
Host: www.example.com
File: new/test.html
Path: new/test.html
URL…
16
Given a URL object, you can retrieve the data associated with it.
To access the actual bits or content information of a URL, create a
URLConnection object from it, using URL classes openConnection()
method.
The openConnection() method has the following general form:
URLConnection openConnection() throws IOException
It returns a URLConnection object associated with the invoking URL
object.
URLConnection
17
Java provides a HTTP client to access resources via the HTTP or HTTPS protocol.
The main class to access the Internet via HTTP/HTTPS is the HttpURLConnection class.
The URL class can be used to define a pointer to a web resource while the
HttpURLConnection class can be used to access a web resource.
HttpURLConnection is a subclass of URLConnection and it provides support for HTTP
connections.
It provides some additional methods that are helpful when working specifically with
http URLs.
You obtain an HttpURLConnection in the same way using URLConnection, by calling
openConnection() on a URL object, but you must cast the result to HttpURLConnection.
Of course, you must make sure that you are actually opening an HTTP connection.
Once you have obtained a reference to an HttpURLConnection object, you can use
any of the methods inherited from URLConnection.
HttpURLConnection…
22
Methods of HttpURLConnection
Methods description
Returns true if redirects are automatically followed and false
static boolean getFollowRedirects()
otherwise. This feature is on by default.
Returns a string representing how URL requests are made. The default
String getRequestMethod()
is GET. Other options, such as POST, are available.
Returns the HTTP response code. –1 is returned if no response code
int getResponseCode()
can be obtained. An IOException is thrown if the connection fails.
Returns the response message associated with the response code.
String getResponseMessage() Returns null if no message is available. An IOException is thrown if the
connection fails.
If how is true, then redirects are automatically followed. If how is false,
static void
redirects are not automatically followed. By default, redirects are
setFollowRedirects(boolean how)
automatically followed.
Sets the method by which HTTP requests are made to that specified by
setRequestMethod(String how) how. The default method is GET, but other options, such as POST, are
available. If how is invalid, a ProtocolException is thrown.
Returns an InputStream that is linked to the resource. This stream can
InputStream getInputStream()
be used to obtain the content of the resource.
HttpURLConnection allows you to create an InputStream.
Once you have access to an InputStream you can read it similarly to an InputStream
from a local file.
The java.net package in the Java platform provides a class, Socket, that
implements one side of a two-way connection between your Java program
and another program on the network.
The Socket class sits on top of a platform-dependent implementation, hiding
the details of any particular system from your Java program.
By using the java.net.Socket class instead of relying on native code, your
Java programs can communicate over the network in a platform-
independent fashion.
2. Sockets…
29
Types of Sockets
There are two kinds of TCP sockets in Java.
One is for servers, and
Methods of ServerSocket
Methods description
InetAddress getInetAddress() It returns the local address occupied by the server socket.
int getLocalPort() It returns the local port occupied by the server socket.
It returns the binding state of the ServerSocket. It returns true returns
boolean isBound()
true if the ServerSocket has ever been bound to a port.
It listens for a connection to be made to this socket and accepts it. The
Socket accept() method blocks until a connection is made. It throws IOException if an
I/O error occurs when waiting for a connection.
Returns the closed state of the ServerSocket. It returns true if the
boolean isClosed()
socket has been closed.
Closes this server socket. Any thread currently blocked in
void close() ServerSocket.accept() will throw a SocketException. It throws
IOException if an I/O error occurs when closing the socket.
Sets the default receive buffer size for sockets accepted by the server
setReceiveBufferSize(int size) socket. This controls the suggested send buffer size used for
network input.
Returns the value of the buffer size that will be used for Sockets
int getReceiveBufferSize()
accepted from this ServerSocket.
2.1 TCP Server Sockets…
33
If you’re finished with a server socket, you should close it, especially if the
program is going to continue to run for some time.
This frees up the port and other programs may use it if necessary.
Closing a ServerSocket should not be confused with closing a Socket.
Closing a ServerSocket frees a port on the local host and it also breaks all
currently open sockets that the ServerSocket has accepted.
Server sockets are closed automatically when a program dies, so it’s not
absolutely necessary to close them.
Nonetheless, it is a good practice to close the socket before the program
ends.
Programmers often follow the approach “close if-not-null” in finally block.
2.1 TCP Server Sockets…
37
The Socket class constructor specifies the host and the port to connect to.
Hosts may be specified as an InetAddress or a String.
Remote ports are specified as int values from 1 to 65535:
Socket(String host, int port) throws UnknownHostException, IOException
Socket(InetAddress host, int port) throws IOException
These constructors connect the server socket i.e. an active network connection
is established to the remote host.
If the connection can’t be opened for some reason, the constructor throws an
IOException or an UnknownHostException.
Example: client connection to a server
try {
Socket ss = new Socket("10.140.150.20", 80);
// send and receive data...
} catch (UnknownHostException ex) {
System.err.println(ex);
} catch (IOException ex) { System.err.println(ex); }
2.2 Client Connection…
40
When you create a server socket, you have to specify a port (e.g. 800) for
the socket.
When a client connects to the server, a socket is created on the client.
This socket has its own local port.
This port number (e.g. 2047) is automatically chosen by the JVM.
To see the local port on the client, you can write the following code on the
client side
System.out.println("local port: " + socket.getLocalPort());
Using Socket, it is possible to check the ports that are occupied and that are available
on your computer.
This can be done using simple port scanner that iterates over all ports and try to
The close() method shuts down both input and output from the socket by
closing the socket.
On occasion, you may want to shut down only half of the connection, either
input or output.
The shutdownInput() and shutdownOutput() methods close only half the
connection:
void shutdownInput()
void shutdownOutput()
Neither actually closes the socket.
Instead, they adjust the stream connected to the socket so that it thinks it’s at
the end of the stream.
Further reads from the input stream after shutting down input return –1.
Further writes to the socket after shutting down output throw an IOException.
2.2 Client Connection…
47
Typically, a server runs continuously on a server computer, and clients from all
over the Internet/LAN can connect to it.
You can use threads to handle the server’s multiple clients simultaneously.
outputToClient.writeDouble(area);
jta.append("Radius received from client: " + radius + '\n');
jta.append("Area computed: " + area + '\n');
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
2.2 UDP Datagrams
55
Some applications that you write to communicate over the network will not
require the reliable, point-to-point channel provided by TCP.
Rather, your applications might benefit from a mode of communication that
delivers independent packages of information whose arrival and order of
arrival are not guaranteed.
The UDP protocol provides a mode of network communication whereby
applications send packets of data, called datagrams, to one another.
Datagrams are bundles of information passed between machines.
A datagram is an independent, self-contained message sent over the
network whose arrival, arrival time, and content are not guaranteed.
Once the datagram has been released to its intended target, there is no
assurance that it will arrive at the destination.
Likewise, when the datagram is received, there is no assurance that it hasn’t
been damaged in transit or that whoever sent it is still there to receive a
response.
2.2 UDP Datagrams…
56
A. DatagramSocket
A DatagramSocket sends as well as receives UDP datagrams.
To send data, you put the data in a DatagramPacket and send the packet
using a DatagramSocket.
To receive data, you take a DatagramPacket object from a DatagramSocket
and then inspect the contents of the packet.
The DatagramSocket themselves are very simple creatures.
In UDP, everything about a datagram, including the address to which it is
directed, is included in the packet itself.
The socket only needs to know the local port on which to listen or send.
DatagramSocket defines four public constructors.
DatagramSocket() – this creates a DatagramSocket bound to any unused
port on the local computer.
DatagramSocket(int port) – creates a DatagramSocket bound to the port
58 specified by port.
DatagramSocket(int port, InetAddress ip) – constructs a DatagramSocket
bound to the specified port and InetAddress.
DatagramSocket(SocketAddress address) – this creates a
DatagramSocket bound to the specified SocketAddress.
InetSocketAddress encapsulates an IP address with a port number.
All can throw a SocketException if an error occurs while creating the socket.
DatagramSocket defines many methods.
Two of the most important are send() and receive():
send(DatagramPacket packet) – this method sends a packet to the
address specified by packet. The DatagramPacket includes information
indicating the data to be sent, its length, the IP address of the remote
host, and the port number on the remote host. It throws IOException if
there is an input-output error.
receive(DatagramPacket packet) – this method waits for a packet to be
received and returns the result. When this method returns, the
DatagramPacket's buffer is filled with the data received. This method
blocks until a datagram is received. It throws IOException if there is an
input output error.
2.2 UDP Datagrams…
59
Method Description
if the socket is connected, then the address is returned. Otherwise,
InetAddress getInetAddress()
null is returned.
int getLocalPort() Returns the number of the local port.
The only difference is the port they bind to: the server socket should bind to
By specifying port 0 you ask Java to pick a random available port for you,
socket.setSoTimeout(10000);
Timeouts are even more important for UDP than TCP because many
B. DatagramPacket
To send data via Java's DatagramSocket you must first create a
DatagramPacket.
DatagramPacket objects store packets of data for sending or store packets
of data received by an application.
DatagramSockets send and receive DatagramPackets.
For sending packets, you can create DatagramPacket using the following
constructors:
DatagramPacket(byte data [], int length, InetAddress ip, int port) - this
specifies a target address and port, which are used by a DatagramSocket
to determine where the data in the packet will be sent.
DatagramPacket(byte data [], int offset, int length, InetAddress ip, int port) –
same as the above method except this transmits packets beginning at the
specified offset into the data.
DatagramPacket(byte[] data, int length, SocketAddress destination) – creates
a datagram packet for sending packets of the given length to the computer
specified by SocketAddress.
DatagramPacket(byte[] data, int offset, int length, SocketAddress destination)
– creates a datagram packet for sending packets of the given length
starting from the given offset. The data is sent to the specified port number
and the machine specified with the given SocketAddress.
DatagramPacket Methods
Method Description
Returns the address of the source (for datagrams being received) or
InetAddress getAddress( )
destination (for datagrams being sent).
64
Returns the byte array of data contained in the datagram. Mostly used
byte[ ] getData( )
to retrieve data from the datagram after it has been received.
Returns the length of the valid data contained in the byte array that
int getLength( ) would be returned from the getData() method. This may not equal the
length of the whole byte array.
int getOffset( ) Returns the starting index of the data.
The method returns an integer specifying the remote port. If this
datagram was received from the Internet, this is the port on the host
int getPort( ) that sent the packet. If the datagram was created locally to be sent to a
remote host, this is the port to which the packet is addressed on the
remote machine.
void setPort(int port) This method sets the port a datagram is addressed to.
Sets the address to which a packet will be sent. The address is specified
setAddress(InetAddress ip)
by InetAddress.
Sets the data to data, the offset to zero, and the length to number of
void setData(byte[ ] data)
bytes in data.
setData(byte[ ] data, int idx,
Sets the data to data, the offset to idx, and the length to size.
int size)
void setLength(int size) Sets the length of the packet to size.
Example: UDP server that sends hello message to all clients
DatagramSocket sock = null;
Scanner sc = new Scanner(System.in);
try {
65 sock = new DatagramSocket(7777);
//buffer to receive incoming data
byte[] buffer = new byte[8192];
DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);
System.out.println("Server socket created. Waiting for incoming data...");
//communication loop
while (true) {
sock.receive(incoming);
byte[] data = incoming.getData();
String str = new String(data, 0, incoming.getLength());
System.out.println("Client: " + str);
System.out.print("Server: ");
String msg = sc.nextLine();
DatagramPacket dp = new DatagramPacket(msg.getBytes(), msg.getBytes().length,
incoming.getAddress(), incoming.getPort());
sock.send(dp);
}
} catch (IOException e) {
System.err.println("IOException " + e);
}
Example: UDP client that can connect to the above UDP server
DatagramSocket sock = null;
String str;
Scanner sc = new Scanner(System.in);
66 try {
sock = new DatagramSocket();
InetAddress host = InetAddress.getByName("localhost");
int port = 7777;
while (true) {
System.out.print("Client: ");
str = sc.nextLine();
byte[] b = str.getBytes();
DatagramPacket dp = new DatagramPacket(b, b.length, host, port);
sock.send(dp);
//now receive reply
byte[] buffer = new byte[8192];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
sock.receive(reply);
byte[] data = reply.getData();
String msg = new String(data, 0, reply.getLength());
System.out.println("Server: " + msg);
}
} catch (IOException e) { System.err.println("IOException " + e); }