Você está na página 1de 9

Networking

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

To initiate a point-to-point client server connection, the Transmission Control


Protocol is used. TCP is a reliable protocol in other words, it guarantees he
delivery of the data it transmits in the form of packets. If a packets are lost or
damaged, TCP will resend data until it verifies that packets have been successfully
transmitted. TCP is needed for applications that must reliably send messages back
and forth or initiate file transfers to ensure that a perfect copy of the data arrives at
the other side uncorrupted.

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

InputStreamReader, BufferedReader and PrintStream class objects are instantiated.


The BufferedReader objects readLine() method is used to retrieve input from the
client and the PrintStream objects println() method is used to send output to the
client.
In the client application a new Socket is created if the servers ServerSocket accepts
the connection request. The connection is requested by instantiating a Socket class
object and passing in the servers IP address or hostname and the selected port as
arguements. Then InputStreamReader, BufferedReader and PrintStream class
objects are instantiated. The BufferedReader objects readLine() method is used to
retrieve input from the server and the PrintStream objects println() method is used
to send output to the server.
To summarize: client-server applications
1. Create a Socket or ServerSocket object and open it over a specified port and
IP address or host name.
2. Instantiate InputStreamReader, BufferedReader and PrintStream objects to
stream data to and from each socket.
3. Read from and write to the stream between the sockets using their agreedupon protocol.
4. Close the input and output streams.
5. Close the Socket or ServerSocket objects.
Codes: SOK_1_Server.java and SOK_1_CLIENT.java

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

Discussion on some of the classes is shown below:

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.

Three commonly used InetAddress factory methods are shown here:


1. static InetAddress getLocalHost() throws UnknownHostException :
The getLocalHost( ) method simply returns the InetAddress object
that represents the
local host (Returns the IP address of the
localhost).
2. static
InetAddress
getByName(String
hostName)
throws
UnknownHostException
:
The getByName( ) method returns an InetAddress for a host name
passed to it (Returns
the IP address for the given host, the host
name can be either a machine name like
something.com or a string
representing its IP address 200.100.23.12). If these
methods
are
unable to resolve the host name, they throw an UnknownHostException.
3. static InetAddress[ ] getAllByName(String hostName) throws
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 cant resolve the name to at least one
address.
4. static InetAddress getByAddress(byte[] addr) throws
UnknownHostException :
It takes an IP address and returns an InetAddress object. Either an
IPv4 or an IPv6
address can be used.
code: InetAddressTest.java

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( )

Returns a string that lists the host name and the


IP address for convenience.s

Remembering the IP address as a sequence of four numbers is difficult. Therefore,


every IP address is associated with a string called domain name. For example, the IP
address 192,18.97.71 is associated with www.java.sun.com. A server keeps the
database of IP addresses and the associated domain names. Such servers are
called Domain Name Servers (DNS).
NOTE: Internet addresses are looked up in a series of hierarchically cached
servers. That means that your local computer might know a particular name-to-IPaddress 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
doesnt 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. 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.

subClass Inet4Address and Inet6Address:


Java includes support for both IPv4 and IPv6 addresses. Because of this, two
subclasses of InetAddress were created: Inet4Address and Inet6Address.
Inet4Address represents a traditional-style IPv4 address. Inet6Address encapsulates
a newer IPv6 address. Because they are subclasses of InetAddress, an InetAddress
reference can refer to either. This is one way that Java was able to add IPv6
functionality without breaking existing code or adding many more classes. For the
most part, you can simply use InetAddress when working with IP addresses because
it can accommodate both styles.

TCP/IP Client Sockets


TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-topoint, stream-based connections between hosts on the Internet. A socket can be
used to connect Javas I/O system to other programs that may reside either on the
local machine or on any other machine on the Internet.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for
clients.
1. The ServerSocket class: It is designed to be a "listener," which waits for clients
to connect before doing anything. Thus, ServerSocket is for servers.
2. The Socket class is for clients: It is designed to connect to server sockets and
initiate protocol exchanges. Because client sockets are the most commonly used by
Java applications, they are examined here.

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, int q)

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.

Client Socket(TCP/IP) Class:


The client socket is implemented in the class Socket. A socket is an end point for
communication between two host machines. A client socket establishes
connection with the server socket. The connection is a reliable, connectionoriented TCP/IP connection. Once a connection is established, methods defined in
SocketImpl class are used to carry out the desired task.
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:

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.

Socket(InetAddress address, int


port, InetAddress localadrs, int
localport)

Creates a socket and connects it to the


specified remote address and remote port.
the socket binds to the local address and
the specified local port.

Socket defines several instance methods.

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:

connect() : allows you to specify a new connection.


isConnected(): returns true if the socket is connected to a server
isBound( ) : returns true if the socket is bound to an address
isClosed( ) : returns true if the socket is closed
close( ) :close a socket, Closing a socket also closes the I/O streams
associated with the socket

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

Você também pode gostar