Java Networking
Java Networking
Client-Server Architecture
Let’s take an example of a file server to understand the core process of a client/server
network, the file server acts as a storage space on the network for the files,
spreadsheets, databases, etc. Instead of storing these records on every individual
computer, the file server allows the clients to store their files on one central computer
and make them sharable. The client-server architecture is beneficial in reducing the
multiple iterations of a single file and allowing the organization to have one centralized
point for every computer to access the same file.
In common language we can say that the socket is one of the most primitive
technologies of computer networking. Sockets are just like an end-point of two-way
communication, which allow applications to communicate using network hardware and
operating systems. However in case of java never get confused with a socket. Socket
classes are used to establish a connection between client program and a server program.
In java there is a java.net package, which provides two types of classes- first is ordinary
socket, which implement the client side connection and second is server socket, which
implement the server side connection.
The main purpose of the server socket is to listen an incoming connection request and
ordinary socket is used to ask to server for the connection. Once a connection between
Service Port no
echo 7
daytime 13
ftp 21
telnet 23
smtp 25
finger 79
http 80
pop3 110
If we consider the range of the port numbers, there are 0 to 65,535 ports available. The
port numbers ranging from 0 - 1023 are reserved ports or we can say that are restricted
ports. All the 0 to 1023 ports are reserved for use by well-known services such as FTP,
telnet and http and other system services. These ports are called well-known ports.
Reserved Sockets
Once connected, a higher-level protocol ensues, which is dependent on which port you
are using. TCP/IP reserves the lower 1,024 ports for specific protocols. Many of these will
seem familiar to you if you have spent any time surfing the Internet. Port number 21 is
for FTP, 23 is for Telnet, 25 is for e-mail, 79 is for finger, 80 is for HTTP, 119 is for
netnews—and the list goes on. It is up to each protocol to determine how a client should
interact with the port.
For example, HTTP is the protocol that web browsers and servers use to transfer
hypertext pages and images. It is quite a simple protocol for a basic page-browsing web
server. Here's how it works. When a client requests a file from an HTTP server, an action
known as a hit, it simply prints the name of the file in a special format to a predefined
port and reads back the contents of the file. The server also responds with a status code
number to tell the client whether the request can be fulfilled and why. Here's an example
of a client requesting a single file, /index.html, and the server replying that it has
successfully found the file and is sending it to the client:
InetAddress
Whether you are making a phone call, sending mail, or establishing a connection across
the Internet, addresses are fundamental. The InetAddress class is used to encapsulate
both the numerical IP address we discussed earlier and the domain name for that
address. You interact with this class by using the name of an IP host, which is more
convenient and understandable than its IP address. The InetAddress class hides the
number inside.
Factory Methods
The InetAddress class has no visible constructors. To create an InetAddress
object,you have to use one of the available factory methods. Factory methods are
merely a convention whereby static methods in a class return an instance of that class.
This is done in lieu of overloading a constructor with various parameter lists when having
unique method names makes the results much clearer. In the case of InetAddress, the
three methods getLocalHost( ), getByName( ), and getAllByName( ) can be used to
create instances of InetAddress. These methods are shown here:
The getLocalHost( ) method simply returns the InetAddress object that represents
the local host. The getByName( ) method returns an InetAddress for a host name
passed to it. If these methods are unable to resolve the host name, they throw an
UnknownHostException.On the Internet, it is common for a single name to be used to
represent several machines. In the world of web servers, this is one way to provide
some degree of scaling.The getAllByName( ) factory method returns an array of
InetAddresses that represent all of the addresses that a particular name resolves to. It
will also throw an UnknownHostException if it can't resolve the name to at least one
address.The following example prints the addresses and names of the local machine and
two well-known Internet web sites:
Applets may only establish socket connections back to the host from which the applet
was downloaded. This restriction exists because it would be dangerous for applets loaded
through a firewall to have access to any arbitrary machine. There are two kinds of TCP
sockets in Java. One is for servers, and the other is for clients. The ServerSocket class
is designed to be a "listener," which waits for clients to connect before doing anything.
The Socket class is designed to connect to server sockets and initiate protocol
exchanges. The creation of a Socket object implicitly establishes a connection between
the client and server. There are no methods or constructors that explicitly expose the
details of establishing that connection. Here are two constructors used to create client
sockets:
A socket can be examined at any time for the address and port information associated
with it, by use of the following methods:
InetAddress getInetAddress( )
Returns the InetAddress associated with the Socket object.
int getPort( )
Returns the remote port to which this Socket object is connected.
int getLocalPort( )
Format
http://www.protech-education.com/ and http://www.protech-
education.com:80/index.html. A URL specification is based on four components. The
first is the protocol to use, separated from the rest of the locator by a colon (:). Common
protocols are http, ftp, gopher, and file, although these days almost everything is being
done via HTTP (in fact, most browsers will proceed correctly if you leave off the "http://"
from your URL specification). The second component is the host name or IP address of
the host to use; this is delimited on the left by double slashes (//) and on the right by a
slash (/) or optionally a colon (:). The third component, the port number, is an optional
parameter, delimited on the left from the host name by a colon (:) and on the right by a
slash (/). (It defaults to port 80, the predefined HTTP port; thus ":80" is redundant.) The
fourth part is the actual file path. Most HTTP servers will append a file named
index.html to URLs that refer directly to a directory resource. Thus,
http://www.protech-education.com / is the same as http://www.protech-
education.com/index.html.
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 urlSpecifier)
The next two forms of the constructor allow you to break up the URL into its component
parts:
URL(String protocolName, String hostName, int port, String path)
URL(String protocolName, String hostName, String path)
Another frequently used constructor allows you to use an existing URL as a reference
context and then create a new URL from that context. Although this sounds a little
contorted, it's really quite easy and useful.
In the following example, we create a URL to Patrick Naughton's home page at Protech-
education
and then examine its properties:
// Demonstrate URL.
import java.net.*;
class URL
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("http://www.protech-education.com/people/naughton/");
System.out.println("Protocol: " + hp.getProtocol());
System.out.println("Port: " + hp.getPort());
System.out.println("Host: " + hp.getHost());
System.out.println("File: " + hp.getFile());
System.out.println("Ext:" + hp.toExternalForm());
}}
Datagrams
It provides a serialized, predictable, reliable stream of packet data. TCP includes many
complicated algorithms for dealing with congestion control on crowded networks, as well
as possible expectations about packet loss. This leads to a somewhat inefficient way to
transport data. Datagrams are bundles of information passed between machines. Once
the datagram has been released to its intended target, there is no assurance that it will
arrive or even that someone will be there to catch it. 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. Java implements datagrams on top of the UDP
protocol by using two classes: The DatagramPacket object is the data container, while
the DatagramSocket is the mechanism used to send or receive the DatagramPackets.
DatagramPacket
DatagramPackets can be created with one of four constructors. The first constructor
specifies a buffer that will receive data, and the size of a packet. It is used for receiving
data over a DatagramSocket. The second form allows you to specify an offset into the
buffer at which data will be stored. The third form specifies a target address and port,
which are used by a DatagramSocket to determine where the data in the packet will be
sent. The fourth form transmits packets beginning at the specified offset into the data.
Think of the first two forms as building an "in box," and the second two forms as stuffing
and addressing an envelope. Here are the four constructors:
import java.net.URL;
import java.net.URLConnection;
//ServerSocket Example
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
String response = "Hello " + s.getInetAddress() + " on port " + s.getPort() + "\r\n";
response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort() + "\r\n";