Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
200 views

Java Networking

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views

Java Networking

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

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 java.net 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 java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("google.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("java2s.com");
for (int i=0; i<SW.length; i++)
System.out.println(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 java.net.*;
import java.io.*;
class Whois
{
public static void main(String args[]) throws Exception
{
int c;
// Create a socket connected to internic.net, port 43.
Socket s = new Socket("internic.net", 43);
// Obtain input and output streams.
InputStream in = s.getInputStream();
OutputStream out = s.getOutputStream();
// Construct a request string.

String str = (args.length == 0 ? "osborne.com" : args[0]) + "\n";


// Convert to bytes.
byte buf[] = str.getBytes();
// Send request.
out.write(buf);
// Read and display response.
while ((c = in.read()) != -1)
{
System.out.print((char) c);
}
s.close();
}
}

 URL(The Uniform Resource Locator)


 The URL provides a reasonably intelligible form to uniquely identify or address information
on the Internet.
 http://www.osborne.com:80/index.htm. 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 or
index.htm 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 java.net.*;
class URLDemo
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("http://www.osborne.com/downloads");
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());
}
}

 To access the actual bits or content information of a URL, create a URLConnection object
from it, using its openConnection( ) method, like this:
urlc = url.openConnection()
 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 connections.This
class is called HttpURLConnection.
Networking

Example: import java.net.*;


import java.io.*;
import java.util.*;
class HttpURLDemo
{
public static void main(String args[]) throws Exception
{
URL hp = new URL("http://www.google.com");
HttpURLConnection hpCon = (HttpURLConnection) hp.openConnection();
// Display request method.
System.out.println("Request method is " + hpCon.getRequestMethod());
// Display response code.
System.out.println("Response code is " +hpCon.getResponseCode());
// Display response message.
System.out.println("Response Message is " +hpCon.getResponseMessage());
// Get a list of the header fields and a set
// of the header keys.
Map<String, List<String>> hdrMap = hpCon.getHeaderFields();
Set<String> hdrField = hdrMap.keySet();
System.out.println("\nHere is the header:");
// Display all header keys and values.
for(String k : hdrField)
{
System.out.println("Key: " + k +" Value: " + hdrMap.get(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

You might also like