[Go to site: main page, start]

0% found this document useful (0 votes)
52 views7 pages

Java Networking Essentials Guide

This document discusses Java networking concepts including: 1) Sockets identify endpoints in a network and allow servers to serve multiple clients simultaneously through the use of ports. 2) Common networking protocols include IP, TCP, and UDP. Well-known port numbers are used for specific applications like FTP, Telnet, email, and HTTP. 3) The InetAddress class represents IP addresses and can resolve host names. URL represents web addresses and can be used to open connections via URLConnection subclasses like HttpURLConnection.

Uploaded by

krishna524
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views7 pages

Java Networking Essentials Guide

This document discusses Java networking concepts including: 1) Sockets identify endpoints in a network and allow servers to serve multiple clients simultaneously through the use of ports. 2) Common networking protocols include IP, TCP, and UDP. Well-known port numbers are used for specific applications like FTP, Telnet, email, and HTTP. 3) The InetAddress class represents IP addresses and can resolve host names. URL represents web addresses and can be used to open connections via URLConnection subclasses like HttpURLConnection.

Uploaded by

krishna524
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
  • Networking Overview
  • InetAddress
  • TCP/IP Client Sockets
  • URL
  • URLConnection
  • HttpURLConnection
  • TCP/IP Server Sockets

Networking

 Java is practically a synonym for Internet programming. There are a number of reasons for this, not
the least of which is its ability to generate secure, cross-platform, portable code.
 This chapter explores the [Link] package. It is important to emphasize that networking is a very
large and at times complicated topic.
 At the core of Java’s networking support is the concept of a socket. A socket identifies an endpoint
in a network.
 Sockets are at the foundation of modern networking because a socket allows a single computer to
serve many different clients at once, as well as to serve many different types of information.
 This is accomplished through the use of a port, which is a numbered socket on a particular machine.
A server process is said to “listen” to a port until a client connects to it. A server is allowed to accept
multiple clients connected to the same port number, although each session is unique.
 To manage multiple client connections, a server process must be multithreaded.
 Socket communication takes place via a protocol. Internet Protocol (IP).
 Internet Protocol (IP) – Low level
 Transmission Control Protocol (TCP) – High level
 Port number 21 is for FTP; 23 is for Telnet; 25 is for e-mail; 43 is for whois; 79 is for finger; 80 is for
HTTP; 119 is for netnews
 A key component of the Internet is the address. Every computer on the Internet has one. An
Internet address is a number that uniquely identifies each computer on the Net.
Networking

 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.
 Three commonly used InetAddress factory methods are shown here:
static InetAddress getLocalHost( ) throws UnknownHostException
static InetAddress getByName(String hostName) throws UnknownHostException
static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException

 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.

 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

 InetAddress also includes the factory method getByAddress( ), which takes an IP address and
returns an InetAddress object
Example 1: import [Link].*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address = [Link]();
[Link](Address);
Address = [Link]("[Link]");
[Link](Address);
InetAddress SW[] = [Link]("[Link]");
for (int i=0; i<[Link]; i++)
[Link](SW[i]);
}
}
Networking

 TCP/IP Client Sockets


 TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point,
stream-based connections between hosts on the Internet. A socket can be used to connect
Java’s 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.
The ServerSocket class is designed to be a “listener,” which waits for clients to
connect before doing anything.
The Socket class is for clients. It 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.

Socket methods

You can gain access to the input and output streams associated with a Socket by use
of the getInputStream( ) and getOuptutStream( ) methods.
Networking
other methods
 connect( ), which allows you to specify a new connection;
 isConnected( ), which returns true if the socket is connected to a server;
 isBound( ), which returns true if the socket is bound to an address;
 isClosed( ), which returns true if the socket is closed.
Example2:
import [Link].*;
import [Link].*;
class Whois
{
public static void main(String args[]) throws Exception
{
int c;
// Create a socket connected to [Link], port 43.
Socket s = new Socket("[Link]", 43);
// Obtain input and output streams.
InputStream in = [Link]();
OutputStream out = [Link]();
// Construct a request string.

String str = ([Link] == 0 ? "[Link]" : args[0]) + "\n";


// Convert to bytes.
byte buf[] = [Link]();
// Send request.
[Link](buf);
// Read and display response.
while ((c = [Link]()) != -1)
{
[Link]((char) c);
}
[Link]();
}
}

 URL(The Uniform Resource Locator)


 The URL provides a reasonably intelligible form to uniquely identify or address information
on the Internet.
 [Link] 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
“[Link] 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 [Link] or
[Link] to URLs that refer directly to a directory resource.
Networking

 URL class constructors


 URL(String urlSpecifier) throws MalformedURLException
 URL(String protocolName, String hostName, int port, String path) throws
MalformedURLException
 URL(String protocolName, String hostName, String path) throws
MalformedURLException
Example 3: import [Link].*;
class URLDemo
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("[Link]
[Link]("Protocol: " + [Link]());
[Link]("Port: " + [Link]());
[Link]("Host: " + [Link]());
[Link]("File: " + [Link]());
[Link]("Ext:" + [Link]());
}
}

 To access the actual bits or content information of a URL, create a URLConnection object
from it, using its openConnection( ) method, like this:
urlc = [Link]()
 openConnection( ) has the following general form:
URLConnection openConnection( ) throws IOException

 URLConnection
 URLConnection is a general-purpose class for accessing the attributes of a remote resource.

 HttpURLConnection
 Java provides a subclass of URLConnection that provides support for HTTP [Link]
class is called HttpURLConnection.
Networking

Example: import [Link].*;


import [Link].*;
import [Link].*;
class HttpURLDemo
{
public static void main(String args[]) throws Exception
{
URL hp = new URL("[Link]
HttpURLConnection hpCon = (HttpURLConnection) [Link]();
// Display request method.
[Link]("Request method is " + [Link]());
// Display response code.
[Link]("Response code is " +[Link]());
// Display response message.
[Link]("Response Message is " +[Link]());
// Get a list of the header fields and a set
// of the header keys.
Map<String, List<String>> hdrMap = [Link]();
Set<String> hdrField = [Link]();
[Link]("\nHere is the header:");
// Display all header keys and values.
for(String k : hdrField)
{
[Link]("Key: " + k +" Value: " + [Link](k));
}
}
}
Networking
 TCP/IP Server Sockets
 The ServerSocket class is used to create servers that listen for either local or remote client
programs to connect to them on published ports.
 When you create a ServerSocket, it will register itself with the system as having an interest
in client connections.
 Constructors

Common questions

Powered by AI

A URL in Java comprises four main components: the protocol, host name/IP address, port number, and file path . The protocol specifies the method of information transmission, commonly HTTP . The host name or IP address identifies the target server . The port number, optional, specifies the port for the connection, with a default for specific protocols (e.g., 80 for HTTP). The file path specifies the exact resource on the server . Together, these components uniquely locate and identify resources on the Internet .

The InetAddress class in Java encapsulates both IPv4 and IPv6 addresses, enabling programs to operate seamlessly across different network configurations . It provides methods like getLocalHost(), getByName(), and getAllByName() to retrieve InetAddress objects representing local or remote hosts by hostname or address . These methods enhance flexibility by allowing Java applications to handle different IP formats and perform operations like resolving domain names to IP addresses, thus abstracting the complexity of network address management .

In Java networking, the ServerSocket class acts as a 'listener' that waits for clients to establish connections, while the Socket class is utilized by clients to connect to server sockets . ServerSocket facilitates the creation of server applications that accept incoming connections on a specific port, whereas Socket allows clients to initiate communication by connecting to a server . Together, they enable bidirectional, persistent, and stream-based connections over the Internet .

The openConnection() method in the URL class is pivotal for network communication as it establishes a connection to a resource and returns a URLConnection instance . This instance allows access to the attributes of the resource, facilitates setting request properties, and manages data transfer by opening streams for input and output. By abstracting the complexity of connection management, openConnection() enables developers to seamlessly interact with various web resources, enhancing application functionality and flexibility .

In Java, sockets gain access to input and output streams through the getInputStream() and getOutputStream() methods . This interaction is fundamental because it allows the socket to receive and send data over the network, enabling bidirectional communication between client and server. These streams provide the mechanism through which Java's I/O system can interact with programs on local or remote machines over the Internet, supporting persistent and reliable data exchange .

Multithreading is essential in Java networking to handle multiple client connections simultaneously . Without multithreading, a server could only process one client request at a time, severely limiting throughput and responsiveness. In Java, server processes manage multithreading by spawning a new thread for each connection that interacts with the server, allowing them to run concurrently and independently. This design is crucial for real-time applications that require managing hundreds or thousands of simultaneous connections efficiently .

Resolving a domain name to an IP address is performed using the getByName() method of the InetAddress class . This method queries DNS servers to translate human-readable domain names into numerical IP addresses, essential for establishing network connections. This process is significant as IP addresses are required for routing data across networks, enabling seamless communication between hosts by abstracting complex numerical addresses into memorable domain names .

Java facilitates Internet programming due to its ability to produce secure, cross-platform, and portable code . Its networking capabilities, rooted in the java.net package, support these benefits by providing robust classes and methods for network communication via sockets . Sockets in Java allow for simultaneous connections from multiple clients, emphasizing concurrency and real-time communication, essential for Internet applications . Furthermore, Java's multithreaded server processes enhance the efficiency and manageability of handling numerous client connections, maintaining the stability and security needed for internet applications .

Java's HttpURLConnection class extends URLConnection by providing specific functionality for HTTP protocol interactions . It supports features such as setting HTTP request methods, retrieving status codes and messages, and managing headers, which are essential for web-based applications that require comprehensive HTTP features. HttpURLConnection simplifies handling of HTTP requests and responses, making it ideal for applications that need to interact with web services and APIs effectively .

Port numbers are crucial in network communications as they help differentiate multiple services on a single device by assigning a numerical identifier to each service . Common examples include port 21 for FTP, port 80 for HTTP, and port 25 for email services. In Java networking, a server 'listens' for client requests on these port numbers, allowing multiple clients to connect simultaneously to services provided on the same port .

Networking 
 
 Java is practically a synonym for Internet programming. There are a number of reasons for this, not 
the leas
Networking 
 
 InetAddress 
 The InetAddress class is used to encapsulate both the numerical IP address and the domain 
nam
Networking 
 
 TCP/IP Client Sockets 
 TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-p
Networking 
 other methods  
 connect( ), which allows you to specify a new connection; 
 isConnected( ), which returns tru
Networking 
 
 URL class constructors 
 URL(String urlSpecifier) throws MalformedURLException 
 URL(String protocolName, S
Networking 
 
 
 
Example:   import java.net.*; 
import java.io.*; 
import java.util.*; 
class HttpURLDemo 
{ 
 
public stat
Networking 
 TCP/IP Server Sockets 
 The ServerSocket class is used to create servers that listen for either local or remot

You might also like