Escolar Documentos
Profissional Documentos
Cultura Documentos
Java is the premier language for Network Programming because it defines many
classes defined in the java.net package which provide an easy to use means by
which programmers of all skill levels can access network resources.
1. Networking Basics
Sometimes an applicationss structure takes on a client-server nature.
application provides services such as access to a database, serving
time, authentication and access to shared resources or serving
conversations. Client applications are then created which make use
services.
A server
network
out chat
of these
TCP/IP Sockets
When establishing connectivity, the client and server each bind a socket to their
end of the connection. Once a connection has been established the client and
server both read from and write to the socket when communicating.
A socket is a combination of both an IP Address and a port number. Each socket
used in client-server communication is an endpoint of the two-way communication
link used to send packets between applications. Multiple TCP connections can be
initiated between each client and a server and each connection is unique by its
combination of ports and endpoints.
The server runs on a specific host where it creates and continuously listens to a
server socket that is bound to a specified port number and waits for clients to
make connection requests. The client must know the correct port and the ip
address or host name of the server to initiate a connection request and identify
itself. When the server accepts the clients connection request, the client also
creates a socket and communication between client and server takes place as both
read from and write to their sockets.
In the server application, once a ServerSocket has been instantiated with a
designated port, a new Socket is created to accept the ServerSockets connect
request by calling the accept() method on the ServerSocket object. Then
Networking Classes:
Java supports both the TCP and UDP protocol families. The classes contained in the
java.net package are shown here:
Authenticator
InetAddress
CacheRequest
SocketAddress
SocketImpl
InetSocketAddress
CacheRespons
e
ContentHandle
r
InterfaceAddress
SocketPermission
StandardSocketOption
JarURLConnection
CookieHandler
MulticastSocket
URI
CookieManage
r
NetPermission
URL
DatagramPack
et
NetworkInterface
URLClassLoader
DatagramSock
URLConnection
et
PasswordAuthenticatio
n
DatagramSock
etImpl
Proxy
URLDecoder
HttpCookie
ProxySelector
URLEncoder
HttpURLConne
ction
ResponseCache
URLPermission (Added
by JDK 8.)
IDN
URLStreamHandler
SecureCacheResponse
Inet4Address
ServerSocket
Inet6Address
Socket
Networking Interfaces:
FileNameMap
SocketOptions
ProtocolFamily
URLStreamHandlerFa
ctory
ContentHandlerFactory
CookiePolicy
CookieStore
SocketImplFactory
SocketOption
DatagramSocketImplFacto
ry
1. InetAddress Class
The IP Address is handled in the class InetAddress. The InetAddress class
is used to encapsulate
both the numerical IP address and the domain name for
that address. InetAddress can handle both IPV4 and IPV6 addresses. We can
interact with this class using the IP host, which is more convenient
than
the
numbered IP address
Factory Methods:
The InetAddress has no visible constructors. To create an InetAddress Object, we
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.
Instance Methods:
The InetAddress class has several other methods, which can be used on the
objects returned by the methods just discussed. Here are some of the more
commonly used methods:
Methods
boolean equals(Object
other)
byte[ ] getAddress( )
String getHostAddress( )
String getHostName( )
boolean
isMulticastAddress( )
Description
Returns true if this object has the same Internet
address as other.
Returns a byte array that represents the objects
IP address in network byte order.
Returns a string that represents the host address
associated with the InetAddress object.
Returns a string that represents the host name
associated with the InetAddress object.
Returns true if this address is a multicast
address. Otherwise, it returns false.
String toString( )
ServerSocket(TCP/IP) class:
This class deals with the server sockets. A server socket keeps waiting for request
calls from the network. When a request is received, it does some operation
appropriate to the request and returns a reply to the caller. The request in
processed by methods defined in SocketImpl class. The connection-established is
connection oriented and governed by TCP.
Constructors:
The constructors used to create server socket are given below. All of them
throw IOException.
Constructor
ServerSocket(int port)
ServerSocket(int
port,
InetAddress address)
int
q,
Description
Creates a server socket on a specified
port; a port 0 creates sockeet on any
free port. The maximum queue length
for incoming connection is set to 50.
Creates a server socket on the specified
port; the maximum queue length is set
to q.
Creates a server socket on the specified
port with a maximum queue length of
q; in a multi-homed host, address
specifies the IP address to which the
socket binds.
Methods:
Some of the methods defined in the ServerSocket are:
Method
InetAddress
getInetAddress()
int getLocalPort()
Socket accept()
. void close()
void setSoTimeout(int
timeout)
int getSoTimeOut()
Description
Returns the local address of this server socket.
Returns the port number on which this socket is
listening.
Listens for a connection to be made to this socket and
accepts it; a new socket is created. It throws an
IOException.
Closes this socket; throws IOException if an I/O error
occurs when closing the socket.
Enables/Disables SO_TIMEOUT with the specified timeout
in milliseconds; with a non-zero timeout, a call to
acccept() for this ServerSocket will block for only this
much amount of time. After the expiry of the timeout,
InterruptedIOException is thrown out. This method will
also throw SocketException.
Returns the SO_TIMEOUT; a 0 value implies that the
option is disabled.
Constructors:
Constructor
Socket(String hostName, int port)
throws UnknownHostException,
IOException
Socket(InetAddress ipAddress, int
port) throws IOException
Description
Creates a stream socket connects to the
specified port number on the specified
host
Creates a stream socket and connects it
to the specified port number at the
specified
IP
address;
throws
an
IOException.
Methods:
Method
InetAddress
getInetAddress( )
InetAddress
getLocalAddress()
int getPort( )
int getLocalPort( )
Description
Returns the InetAddress associated with the Socket
object (returns the IP address to which the
socket is connected). It returns null if the socket
is not connected.
Returns he local address to which the socket is
connected.
Returns the remote port to which the invoking
Socket object is connected (or returns the remote
port number to which the socket is
connected). It returns 0 if the socket is not
connected.
Returns the local port to which the invoking Socket
(or returns the local port number to which the
socket is connected object is bound. It returns 1
if the socket is not
void close()
InputStream
getInputStream( )
throws IOException
OutputStream
getOutputStream()
bound.
Closes this socket; throws an IOException
Returns the InputStream associated with the
invoking socket (Returns an input stream for
reading bytes from the socket, throws an
IOException).
Returns the OutputStream associated with the
invoking socket (Returns an output stream for
writing bytes to the socket; throws an
IOException).
We can get access to the input and output streams associated with a Socket by
use of the getInputStream( ) and getOuptutStream( ) methods, as shown
above. Each can throw an IOException if the socket has been invalidated by a
loss of connection. These streams are used exactly like the I/O streams (described
in Chapter 20 of the complete reference book, 9 th ed) to send and receive
data.
Some other
1.
2.
3.
4.
5.
methods are:
Socket also implements AutoCloseable, which means we can use try-withresources block to manage a socket.
The following program provides a simple Socket example. . It opens a connection
to a "whois" port (port 43) on the InterNIC server, sends the command-line
argument down the socket, and then prints the data that is returned.
Code : Whois.java
Note, that in the code we have use close(), explicitly, using try-with-resources
statement, we can avoid close().
Code:Whois_try.java
In this maethod, exceptions are still thrown by main(),but they could be handled by
adding catch clauses to the end of the try-with-resources block.
URL Class:
URL stands for Uniform Resource Locator. URL unifies many higher-level protocols
and file formats into a single form called web or World Wide Web. The URL provides
a reasonably intelligible form to uniquely identify or address information on the
Internet. All URLs share the same basic format, although some variation is allowed.
Here are two examples: http://www.MHProfessional.com/ and
http://www.MHProfessional.com:80/index.htm. A URL specification is based on
four components, Protocol://hostname:port_number/file.
Within Javas network class library, the URL class provides a simple, concise API to
access information across the Internet using URLs.
Constructors:
Javas URL class has several constructors and each can throw a
MalformedURLException.
Constructor
URL(String urlspecifier)
throws
MalformedURLException
URL(URL context, String
spec)
Description
creates a URL object from the String specification
spec;
Creates a URL by parsing the specification spec
within a specified context