Abstract on Socket Programming
-
Upload
yogeshyadav2012 -
Category
Documents
-
view
119 -
download
2
Transcript of Abstract on Socket Programming
Abstract
One of the most basic network programming tasks you’ll likely face as a Java programmer is
performing socket functions. You may have to create a network client that talks to a server via a
socket connection. Or, you may have to create a server that listens for socket connections. This
report illustrates several examples on the two types of socket APIs:
connectionless datagram sockets and connection-oriented stream-mode
sockets. With datagram sockets, communication occurs in the form of
discrete messages sent from the sender to receiver; whereas with stream-
mode sockets, data is transferred using the concept of a continuous data
stream flowing from a source to a destination. For both kinds of sockets, we
illustrate examples for simplex (one-way) and duplex (bi-directional)
communication. We also explain in detail the difference between a
concurrent server and iterative server and show example programs on how
to develop the two types of servers, along with an example. The last section
of the report describes the Multicast Socket API in Java and illustrates
examples for multicast communication
1
Introduction
Interprocess communication (IPC) is the backbone of distributed computing.
Processes are
runtime representations of a program. IPC refers to the ability for separate,
independent
processes to communicate among themselves to collaborate on a task.
System Design goes through logical and physical stages of development. Logical reviews the
present physics system, prepare input-output specification, detail implementation plan, a logical
design walkthrough.
The physical system maps out the details of the physical system, plans, the system
implementation and specification of any hardware and software. System design is highly creative
process, which can be greatly facilitated by the following stages:
1. Proper problem definition.
2. Set of requirements of the new system.
3. Overall design of the whole system
During analysis the focus is on what needs to be done, independent of how it is done. During
design, decisions are made about how the problem will be solved, first at a high level, then at
increasingly detailed level.
System design is the first stage in which the basic approach to solving the problem is selected.
During system design, the overall structure and style is decided. The System architecture is the
overall organization of the system into components called sub-systems. The architecture provides
the context in which more detailed decisions are made in later design stages. By making high
level decisions that apply to the entire system, the system designer partitions the problem into
sub-systems so that several designers working independently on different subsystems can do
further work.
2
The system designer must make the following decisions:
Organize the system into subsystem
Strategy for data stores (Data structure)
Basic architecture for system
SYSTEM DESIGN
The whole “FTP Client and Server application” can be divided into following subsystems.
Client UI - This subsystem should provide the complete User interface for the user to
Download and Upload a file on the Server. So this subsystem again can be divided into
following subsystems
Defining protocol for data transfer : In this subsystem we define a simple protocol for
data transfer from client to server and server to client.
Networking of the clients: This subsystem is responsible for networking of the all the
clients and multithreading of the application to avoid data corruption and inconsistency.
Identify concurrency inherent in the system:
For handling this problem we have to make that function synchronized which modify on server
data structure.
For each user we have a different thread, which is maintaining list of operations and sending the
operation to client one by one.
Notification of Server to Client:
Whenever server is notifying any operation to Client. The operation is modifying data
structure of Client in different thread so client needs not to stop his work when server is
notifying any operation to client.
Notifying from client to server:
Whenever client is notifying any operation to server that’s going on in different thread.
3
Basic architecture for system:
In this section we define basic architecture of implementation. Whole design of our application
can be divided in two basic parts.
Architecture of FTPClient We use AWT for designing UI part of Client side.
Architecture of FTPServer (for making networked) We use socket programming for making
our application networked.
Java’s Networking protocol: TCP/IP:
Java’s view of networking means TCP/IP. TCP/IP stands for Transmission-Control Protocol/
Internet Protocol, the two data communication protocols on which the Internet relies for all its
functionality. In practice however, TCP/IP stands for a whole collection of related protocols, all
based around TCP and IP.
IP: Whatever application protocol is used to implement some internet service, IP relies at the
heart of all Internet data communications. IP is a datagram protocol, which means that
transmitted packets of information (packets, for short) are not guaranteed to be delivered. IP
packets also do not form part of a stream of related packets; IP is a connectionless protocol. Each
IP packet travel on its own, like an individual letter in a postal network.
An IP packet can be a maximum of 64KB long.
TCP: For Guaranteed delivery: Since IP packets are never guaranteed to arrive at their
destination, a high level protocol, TCP is used to provide a basic service that does guarantee
delivery. TCP manages this by using IP as a building block.
Wherever IP is a datagram service, TCP presents a connection-oriented data stream service (like
the telephone network). Before sending data via TCP, a computer needs to connect with the
computer at the other end; only then can data be exchanged. Another difference is that the TCP
protocol allows you to send or receive arbitrary amounts if data as one big stream of byte data. IP
is theoretically limited to sending 65,536 byte packet, which would be insufficient for sending
many files or even many large GIF images embedded in web pages. TCP solves this problem by
4
breaking up the user’s data stream into separate IP packets, numbering them, and then
reassembling them on arrival. This is the function of the sequence number and sequence
acknowledges number fields.
The most important TCP header fields, from user’s stand point are the source and destination
port fields, while IP allows you to send an IP packet to an individual machine on the network.
TCP forces you to refine this addressing by adding some destination port address every machine
that talks TCP/IP has 65,536 different TCP ports (or socket) it can talk through.
A large collection of standard port numbers has been defined. Following table shows some port
addresses for familiar Internet services.
Port Name Port No. Service descriptionEcho 7 Echoes whatever you send to it.Discard 9 Discards whatever you send itDaytime 13 Produces destination machine’s local timeQotd 17 Produce the “quote of the day” for that m/c.chargen 19 Produce a test stream of charactersftp 21 FTP porttelnet 23 Telnet protocol portSmtp 25 SMTP portFinger 79 Finger protocol porthttp 80 Web server portPop3 110 POP version 3 portnntp 119 NNTP port
Java’s networking (Package java.net):Java has very good features for TCP/IP based data transmission. Most of the classes used for
network based data transmission are available in java.net package.
Most useful classes of this package are given below:
DatagramPacket This class represents a datagram packet.
DatagramSocketThis class represents a socket for sending and receiving datagram packets.
5
InetAddress This class represents an Internet Protocol (IP) address.
ServerSocket This class implements server sockets.
Socket This class implements client sockets (also called just "sockets").
Identifying objects and classes: FTPServer
FTPClient
Graphical User Interface Formats
FTPClient:
Input dialog for Server Location
6
FTPCLIENT GUI
7
Download Save FileDialogBox
8
Upload File Selection DialogBox
9
Downloading In Progress.
10
FTPSERVER Console
11
Event Flow Diagram:
Event Flow Diagram
Identify Constraints:
Performance ConstraintsSpeed in transferring data among various clients. Because data is getting shared among various clients, speed of data transfer must be fast enough.4KB data send at a time.
Time Constraints
The project should be completed in fifteen days time duration.
12
FTP Client
FTP ServerOther FTP Clients
1. Send connection information. 2. Notify operation
Send connection confirmation to client
Notification of operation
Object Design
Introduction:
The analysis phase determines what the implementation must do and the system design phase
determines the plan of attack. The object design phase determines the full definitions of the
classes and associations used in the implementation, as well as the interfaces and algorithms
of the methods used in the implementation of operations. The object design phase adds
internal objects for implementation and optimizes data structure and algorithms. Object
design is analogous to the preliminary design phase of the traditional software development
life cycle.
During object design the designer carries out the strategy chosen during system design and
fleshes out the details. There is a shift in emphasis from application domain concepts towards
computer concepts. The objects discovered during system design serve as the skeleton of the
design but the object designer must choose among different ways to implement them with an
eye towards minimizing execution time, memory and measure of costs. During object design
approach of solution is given as the algorithm with decomposing the complex operations into
simpler smaller internal operation. The classes, attributes, and associations from analysis
must be implemented as specific data structures. New object must be introduced to store
intermediate results during program execution and to avoid the need for re-computation.
Optimization of the design should not be carried to excess, as ease of implementation;
maintainability and extensibility are also important concerns.
Steps of object design:
Detailed design of User interface module
Detailed design for network protocol
Detailed design for classes
13
Detailed design for User Interface Module:
This document intends to provide information about the user interface of the “FTP Server &
Client Application ”. The FTP application has two parts – the client part and the server part.
Using AWT we developed Client UI part.
FTP Client side:
Initializes its components like TextField for writing commands and display them.
Initializes a Text area to show the command list.
Two buttons to upload and download a file from the FTP Server.
Makes a connection back to the FTP server from where it originated by opening a socket.
1. If the step 2 encounters a problem, then it displays the error message to the user
and quits.
2. Else it starts a new thread that listens infinitely for the incoming commands.
This application contains following visual elements:
1. A TextField for writing the commands.
2. Two button A upload button & second is download button.
3. A component TextArea at the center to display the entire coming commands with file
name.
FTP Server Side:
Server Maintain all the incoming commands by the client and send the appropriate
message according their commands.
When server get a command Download to download and Upload to upload a file from
the server or client then its open a new port on the client side to send the file data on end.
This Project is designed on the actual FTP based protocol.
14
Documentation of JavaAPI
1. Input / Output in Java
Streams:Java programs perform I/O through streams. A stream in an abstraction that either produces or
consumes information. A stream is linked to a physical device by the Java I/O system. All
streams behave in the same manner, even if the actual physical devices to which they are linked
differ. Thus, the same I/O classes and methods can be applied to any type of device. This means
an input stream can abstract many different kinds of input from a disk file, a keyboard or a
network socket. Likewise an output stream may refer to the console, a disk file, or a network
connection.
Streams are a clean way to deal with input/output without having every part of your code
understand the difference between a keyboard and a network, for example. Java implements
streams within class hierarchies defined in the java.io package.
Input and Output streams:
Java streams are classified into two basic types: normally input streams and output streams.
An input stream extracts (i.e. reads) data from the source and sends it to the program.
Input Stream (Reads)
(a) Reading Data into a programSimilarly, an output stream takes data from the program and sends (i.o.writes) it to the destination.
Output Stream (writes)
(b) Writing data to a destination
The program connects and opens an input stream on the data source and then reads the data
serially. Similarly, the program connects and opens an output stream to the destination place of
data and writes data out serially. In both the cases, the program does not know the details of end
points (i.e. source and destination).
15
Source Program
Program Destination
Byte Stream and Character Streams:
Java 2 defines two types of stream: Byte and Character. Byte streams provide a convenient
means for handling input and output of bytes. Byte streams are used, for example, when reading
or writing binary data. Character streams provide a convenient means for handling input and
output of character. They use Unicode and therefore, can be internationalized. Also, in some
cases, character streams are more efficient than byhte streams.
The original version of Java (Java 1.0) did not include character streams and thus, all I/O was
byte oriented. Character streams were added by Java 1.1 and certain byte oriented classes and
methods were deprecated.
One other point: at the lowest level, all I/O is still byte oriented. The character-based streams
simply provide a convenient and efficient means for handling characters.
These two groups may be further classified based on their purposes. Byte stream and Character
stream classes contain specialized classes to deal with input and output operations independently
on various tyupes of devices. We can also cross-group the streams based on the type of source or
destination they read from or write to. The source (or destination) may be memory, a file or a
pipe.
Methods of InputStream class:
int available() Gives the number of bytes available in the input (must be overridden by the subclasses).
void close() Closes this input stream and releases any system resources associated with the stream (Endorsing).
void mark(int readlimit) Marks the current position in this input stream.
boolean markSupported() Tests if this input stream supports the mark and reset methods.
abstract int
read() Reads the next byte of data from the input stream.
int read(byte[] b) Reads some number of bytes from the input stream and stores them into the buffer array b.
int read(byte[] b, int off, int len) Reads up to len bytes of data from the input stream into an array of bytes.
16
void reset() Repositions this stream to the position at the time the mark method was last called on this input stream.
long skip(long n) Skips over and discards n bytes of data from this input stream.
Note that the class DataInputStream extends FilterInputStream and implements the interface DataInput. Therefore, the DataInputStream class implements the methods described in DataInput in addition to using methods of InputStream class.The DataInput interface contains the following methods:
boolean readBoolean() Reads one input byte and returns true if that byte is nonzero, false if that byte is zero.
byte readByte() Reads and returns one input byte.
char readChar() Reads an input char and returns the char value.
double readDouble() Reads eight input bytes and returns a double value.
float readFloat() Reads four input bytes and returns a float value.
void readFully(byte[] b) Reads some bytes from an input stream and stores them into the buffer array b.
void readFully(byte[] b, int off, int len) Reads len bytes from an input stream.
int readInt() Reads four input bytes and returns an int value.
String readLine() Reads the next line of text from the input stream.
long readLong() Reads eight input bytes and returns a long value.
short readShort() Reads two input bytes and returns a short value.
String readUTF() Reads in a string that has been encoded using a modified UTF-8 format.
int skipBytes(int n) Makes an attempt to skip over n bytes of data from the input stream, discarding the skipped bytes.
17
A FilterInputStream contains some other input stream which it uses as its basic source of data,
possibly transforming the data along the way providing additional functionality. The class
FilterInputStream itself simply overrides all methods of InputStream with versions that pass all
requests to the contained input stream. Sub-classes of FilterInputStream may further override
some of these methods and may also provide additional methods and fields.
Input stream classes summery:
InputStreamThis abstract class is the superclass of all classes representing an input stream of bytes.
BufferedInputStreamA BufferedInputStream adds functionality to another input stream-namely, the ability to buffer the input and to support the mark and reset methods.
ByteArrayInputStream
A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream.
DataInputStreamA data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way.
FileInputStream A FileInputStream obtains input bytes from a file in a file system.
FilterInputStreamA FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality.
PipedInputStreamA piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream.
PushbackInputStreamA PushbackInputStream adds functionality to another input stream, namely the ability to "push back" or "unread" one byte.
SequenceInputStreamA SequenceInputStream represents the logical concatenation of other input streams.
ObjectInputStreamAn ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream.
RandomAccessFileInstances of this class support both reading and writing to a random access file.
18
Output Stream Classes:Output stream classes are derived from the base class OutputStream, which is an abstract class.
The OutputStream includes methods that are designed to perform the following tasks:
Writing bytes
Closing streams
Flushing streams
Methods of the OutputStream methods:
void close() Closes this output stream and releases any system resources associated with this stream.
void flush() Flushes this output stream and forces any buffered output bytes to be written out.
void write(byte[] b) Writes b.length bytes from the specified byte array to this output stream.
void write(byte[] b, int off, int len) Writes len bytes from the specified byte array starting at offset off to this output stream.
abstract void
write(int b) Writes the specified byte to this output stream.
The DataOutputStream is a counter part of DataInputStream, implements the DataOutput interface and therefore, implements the following methods contained in the DataOutput interface:
void writeBoolean(boolean v) Writes a boolean value to this output stream.
void writeByte(int v) Writes to the output stream the eight low- order bits of the argument v.
void writeBytes(String s) Writes a string to the output stream.
void writeChar(int v) Writes a char value, which is comprised of two bytes, to the output stream.
void writeChars(String s) Writes every character in the string s, to the output stream, in order, two bytes per character.
void writeDouble(double v) Writes a double value, which is comprised of eight bytes, to the output stream.
void writeFloat(float v) Writes a float value, which is comprised of four bytes, to the output stream.
void writeInt(int v)
19
Writes an int value, which is comprised of four bytes, to the output stream.
void writeLong(long v) Writes a long value, which is comprised of eight bytes, to the output stream.
void writeShort(int v) Writes two bytes to the output stream to represent the value of the argument.
void writeUTF(String str) Writes two bytes of length information to the output stream, followed by the modified UTF-8 representation of every character in the string s.
Output Stream Classes Summery:
OutputStreamThis abstract class is the superclass of all classes representing an output stream of bytes.
BufferedOutputStream The class implements a buffered output stream.
ByteArrayOutputStream
This class implements an output stream in which the data is written into a byte array.
DataOutputStreamA data output stream lets an application write primitive Java data types to an output stream in a portable way.
FileOutputStreamA file output stream is an output stream for writing data to a File or to a FileDescriptor.
PipedOutputStreamA piped output stream can be connected to a piped input stream to create a communications pipe.
PrintStreamA PrintStream adds functionality to another output stream, namely the ability to print representations of various data values conveniently.
RandomAccessFileInstances of this class support both reading and writing to a random access file.
20
DataOutput
DataOutputStream
BufferedOutputStream PrintStream
The Character stream classes:Character streams are defined by using two class hierarchies. At the top are two abstract classes:
Reader and Writer. These abstract classes handle Unicode character streams. The Java has
several concrete subclasses of each of these. The abstract Reader and Writer classes define
several key methods that the other stream classes implement. Two of the most important
methods are read() and write(), which read and write characters of data, respectively. These
methods are overridden by derived stream classes.
Reader stream classes:
Reader stream classes are designed to read character from the files. Reader class is the base class
for all other classes in this group. These classes are functionally very similar to the input stream
classes, except input streams use bytes as their fundamental unit of information, while reader
streams use characters.
The Reader class contains methods that are identical to those available in the InputStream class.
Therefore, Reader classes can perform almost all the functions implemented by the input stream
classes.
Reader Stream Classes Summery:
Reader Abstract class for reading character streams.
BufferedReaderRead text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
CharArrayReaderThis class implements a character buffer that can be used as a character-input stream.
FileReader Convenience class for reading character files.
FilterReader Abstract class for reading filtered character streams.
InputStreamReaderAn InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.
PipedReader Piped character-input streams.
PushbackReaderA character-stream reader that allows characters to be pushed back into the stream.
StringReader A character stream whose source is a string.
21
Writer Stream Class:
The writer class is an abstract class which acts as a base class for all the other write stream class.
The base class provides support for all output operations by defining methods that are identical
to those in OutputStream class.
Writer Stream classes summery:
Writer Abstract class for writing to character streams.
BufferedWriterWrite text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
CharArrayWriter This class implements a character buffer that can be used as an Writer.
FileWriter Convenience class for writing character files.
FilterWriter Abstract class for writing filtered character streams.
OutputStreamWriterAn OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset.
PipedWriter Piped character-output streams.
PrintWriter Print formatted representations of objects to a text-output stream.
StringWriterA character stream that collects its output in a string buffer, which can then be used to construct a string.
File:Although most of the classes defined by java.io operate on streams, the File class does not. It
deals directly with files and the file system. That is, the file class does not specify how
information is retrieved form or stored in files. It describes the properties of a file itself.
A File object is used to obtain or manipulate the information associated with a disk file, such as
the permissions, time, date, and directory path, and to navigate sub-directory hierarchies.
Although there are severe restrictions on their use within applets for security reasons, files are
still a central resource for staring persistent and shared information.
A directory in Java is treated simply as a file with one additional property- a list of filenames that
can examined by the list() method.
The following constructors can be used to create File objects:
22
File(String directoryPath)
File(String directoryPath, String filename)
File(File dirObj, String filename)
File(URI uriObj)
Utility methods of File class:
boolean renameTo(File newName)This method, renames the filename of the file corresponding to invoking file object to
newName. It will return true upon success and false if the file cannot be renamed (if you either attempt to rename a file so that it moves from one directory to another or use an existing file, for example).
boolean delete()This method deletes the disk file represented by the path of the invoking file object. You
can also use delete() to delete a directory if the directory is empty. delete() returns true if it deletes the file and false if the file cannot be removed.
void DeleteOnExit() Requests that the file or directory denoted by this abstract pathname be deleted when the virtual machine terminates.
boolean isHidden() Returns true if the invoking file is hidden, otherwise returns false.
boolean setLastModified(long millisec) Sets the time stamp on the invoking file to that specified by millisec, which is the no. of milli-seconds from January, 1970, Co-ordinated Universal Time (UTC).
boolean SetReadOnly() Marks the file or directory named by this abstract pathname so that only read operations are allowed.
23
Java Networking
INTRODUCTION
This chapter explores the java.net package, which provides support for networking. Its creators
have called Java “Programming for the Internet”. While true, there is actually very little in java,
programming language, that makes it any more appropriate for writing Networked Programs
than, say C++ or FORTRAN. What makes Java a good language for networking are the classes
defined in the java.net package.
Socket Overview
A network socket is a lot like an electrical socket. Various plugs around the network have a
standard way of delivering their payload. Anything that understands the standard protocol can
“plug in” to the socket and communicate. With electrical sockets, it doesn’t matter if you plug in
a lamp or a toaster; as long as they are expecting 50Hz, 220-volt electricity, the devices will
work. Think how your electric bill is created. There is a meter somewhere between your house
and the rest of the network. For each kilowatt of power that goes through that meter, you are
billed. The bill comes to your “address” So even though the electricity flows freely around the
power grid; all of the sockets in your house have a particular address.
The same idea applies to network sockets, except we talk about TCP/IP packets and IP addresses
rather than electrons and street addresses. All the sockets have a specific IP address. But one
machine can have many sockets and each socket needs to be identified uniquely. This is done
with the help of port number. Each socket is associated with a unique port number.
Client/Server
A Computer, which requests for some service from another computer, is called a client. The one
that processes the request is called as server. A server waits till one of its clients makes a request.
It can accept multiple connections at a time to the same port number. Multi-threading is used to
24
serve multiple users at the same time. The popular client-sever architecture is based on this
approach.
Reserved Sockets
Once client is connected with the server, a higher –level protocol follows, 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 SMTP, 80 is for HTTP and the list goes on. It is up to each
protocol to determine how a client should interact with the port.
Internet Addressing
Every computer on the Internet has a unique IP address. An IP address is a 32-bit number, which
has four numbers separated by periods. It is possible to connect to the Internet either directly or
through ISP (Internet Services Provider). For connecting directly to the Internet, the computer is
assigned with a permanent IP address. In case connection is made using ISP, it assigns a
temporary IP address for each Session.
Domain Name Service (DNS)
It is very difficult to remember a set of numbers (IP address) to connect to the Internet. The
Domain Naming Service (DNS) is used to overcome this problem. It maps are particular IP
address to a string of characters.
Just as the four numbers of an IP address describe a network hierarchy from left to right, the
name of an Internet address, called its domain name, describe a machine’s location in a name
space, from right to left. For example, www.microsoft.com is in the COM domain, it is called
microsoft after the company name, and www is the name of the specific computer that is
Microsoft’s web server.
25
Java and the Net (java.net package)
The InetAddress Class
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 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 static methods can be used to create instance
of InetAddress.
These methods are shown here:
static InetAddress getLocalHost() throws UnknownHostException
static InetAddress getByName(String hostName) throws UnknownHostException
static InetAddress[] getAllByName(String hostName) throws UnknownHostException
Instance Methods
boolean equals(Object other)
Returns true if this object has the same Internet address as other.
byte[] getAddress()
Returns a four-element byte array that represents the object’s Internet address in network
byte order.
String getHostAddress()
26
Returns a string that represent the host address associated with the InetAddress object. (eg
172.16.1.1)
String getHostName()
Returns a string that represents the host name associated with the InetAddress object. (eg
everest.devnet.com)
int hashCode()
Returns the hashcode of the invoking object.
String toString()
Returns a string that lists the host name and the IP address for convenience
Internet addresses are looked up in a series of hierarchically cached servers. That means that
your local computer might know a particular name-to-IP-address mapping automatically, such as
for itself and nearby servers. For other names, it may ask a local DNS server for IP address
information. If that server doesn’t have a particular address, it can go to a remote site and ask for
it. This can continue all the way up to the root server, called InterNIC (internic.net). This process
might take a long time, so it is wise to structure your code so that you cache IP address
information locally rather than look it up repeatedly.
The URL Class
URL stands for Uniform Resources Locator and it points to resource files on the Internet. The
term Web is often used when there is a discussion about the Internet. The web is a collection of
higher-level protocols and file formats.
An important aspect of a web is its ability to locate files on the Internet. The URL helps in
locating such files using their addresses on the net. Java provides URL class that provides an API
to access information across the Internet.
Components of URL
1. Protocol: HTTP, SMTP, FTP etc.
2. IP Address or the Host Name
3. Port Number
27
4. Actual File Path.
Constructors
Java’s URL class has several constructors and each can throw a MalformedURLException.
URL (String urlSpecifier)
URL (String protocolName, String hostname, int port, String path)
URL (String protocolName, String hostname, String path)
Methods
String getProtocol()
String getHost()
String getFile()
String toExternalForm()
int getPort()
InputStream openStream()
URLConnection openConnection()
TCP Based Classes:
The TCP protocol is not symmetrical like UDP protocol. It uses two types of sockets: Client
Socket on the client side and Server Socket on the server side.
Client socket performs the following basic operations:
Connecting to a remote machine/server (i.e. preparing to send or receive data)
Send data
Receive data
Close a Connection
The Java Socket class which is used by both client and server has methods that correspond to the
above four operations.
28
Server socket performs the following basic operations:
Binding to a port
Listening for incoming data
Accept connections from remote machines/clients on the bound port.
The Java ServerSocket class which is used by the server has methods that correspond to above
three operations.
The Socket Class
This class represents the client socket. Client sockets are normally used in the following fashion:
The new Socket is created using a Socket() Constructor.
The Socket attempts to connect to a remote host.
Once the connection is established the local and remote hosts get input and output
streams from the socket and use those streams to send data to each other. This connection
is full duplex; both hosts can send and/or receive data simultaneously.
When the transmission of data is complete, one or both sides close the connection.
Constructors
public Socket (String host, int port) throws IOException, UnknownHostException
public Socket(InetAddress host, int port) throws IOException, UnknownHostException
public Socket(String host, int port, InetAddress interface, int localport)
throws IOException, UnknownHostException
public Socket(InetAddress host, int port, InetAddress interface, int localport)
throws IOException, UnknownHostException
Methods
public InetAddress getInetAddress()
public int getPort()
29
public int getLocalPort()
public InetAddress getLocalAddress()
InputStream getInputStream()
OutputStream getOutputStream()
public String toString()
The ServerSocket Class
Java provides a ServerSocket class to allow you to write servers. Basically a server socket’s job
is to sit by the phone and wait for incoming calls. Each ServerSocket listens on a particular port
on the local host.
When a client socket on a remote host attempts to connect to that port, the server wakes up,
negotiates the connection between the client & the server and opens a regular socket between
two hosts.
Server Socket waits for connection while client sockets initiate connections. Once the server
socket has setup the connection, the server uses a regular socket to send data to the client. Data
always travels over the regular socket.
The Basic Life Cycle of a Server
1. A new ServerSocket is created on a particular port using a ServerSocket constructor.
2. The ServerSocket listens for incoming connection attempts on that port using it’s accept()
method. The accept() method blocks until a client attempts to make a connection at which
point accept() returns a socket object that connects the client to server.
3. Depending on the type of server either the socket’s getInputStream() method, or
getOutputStream() method or both are called to get input and output streams that
communicates with the client.
4. The server and the client interact according to an agreed upon protocol until it is time to
close the Connection.
5. The server, the client or both, close the connection.
30
6. The server returns to step 2 and waits for next connection.
In Java, you should use a thread to interact with the client so that the server can be ready to
process the next cnnection sooner. Threads place far smaller loads on the server than a complete
child process.
The O.S Stores incoming connections addressed to a particular port in a first-in first-out (FIFO)
queue. The default length of the queue is normally 50 through this can very from OS to OS.
Several ServerSocket constructors allow you to change the length of the queue if its default
length is not large enough; however you want be able to increase the queue beyond the
maximum size that your OS supports.
Constructors
public ServerSocket(int port) throws IOException, BindException
public ServerSocket(int port, int queuelength) throws IOException, BindException
public ServerSocket(int port, int queuelength, InetAddress bindAddress)
throws IOException, BindException
Methods
public Socket accept()
When your setup is done, and you are ready to accept a connection, call the ServerSocket’s
accept() method. This method blocks; it stops the flow of execution and waits until a client
connects.
When a client does connect, the accept() method return a Socket object. You use the streams
returned by this Socket’s getInputStream() and getOutputStream() methods to communicate
with the client.
31
public void close() throws IOException
This method is used to close the Connection.
public InetAddress getInetAddress()
Returns the InetAddress object of the host on which ServerSocket is created.
public int getLocalPort()
Returns the port number on which the ServerSocket is listening for incoming requests.
32
References:
Complete Reference by ‘Herbert Schildt’. Java Programming by ‘James Gosling’. Various Sites related to Networking.
33