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

Java Networking

Client-server architecture involves clients connecting to a central server. In Java, sockets represent these connections and allow clients and servers to communicate over a network. Server sockets listen for incoming connection requests from clients on specific ports, while client sockets initiate connections to servers. Common ports are reserved for specific protocols like HTTP (port 80) and FTP (port 21) to ensure consistent connections.

Uploaded by

rohitdhande79
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

Java Networking

Client-server architecture involves clients connecting to a central server. In Java, sockets represent these connections and allow clients and servers to communicate over a network. Server sockets listen for incoming connection requests from clients on specific ports, while client sockets initiate connections to servers. Common ports are reserved for specific protocols like HTTP (port 80) and FTP (port 21) to ensure consistent connections.

Uploaded by

rohitdhande79
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

JAVA Networking Concepts

Client-Server Architecture

Client-server architecture can be considered as a network environment that


exchanges information between a server machine and a client machine where server has
some resources that can be shared by different clients.

In a Client/server architecture individual computers (known as clients) are connected to


a central computer which is known as “server”.

Let’s take an example of a file server to understand the core process of a client/server
network, the file server acts as a storage space on the network for the files,
spreadsheets, databases, etc. Instead of storing these records on every individual
computer, the file server allows the clients to store their files on one central computer
and make them sharable. The client-server architecture is beneficial in reducing the
multiple iterations of a single file and allowing the organization to have one centralized
point for every computer to access the same file.

The interaction between a lamp and an electrical socket can be considered as an


interaction between client and server is just like. In the example the electrical socket is
just like a server and the lamp works like a client.

Socket and ports

In common language we can say that the socket is one of the most primitive
technologies of computer networking. Sockets are just like an end-point of two-way
communication, which allow applications to communicate using network hardware and
operating systems. However in case of java never get confused with a socket. Socket
classes are used to establish a connection between client program and a server program.
In java there is a java.net package, which provides two types of classes- first is ordinary
socket, which implement the client side connection and second is server socket, which
implement the server side connection.

The main purpose of the server socket is to listen an incoming connection request and
ordinary socket is used to ask to server for the connection. Once a connection between

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268) Page 1


client and server established, both the connected socket can communicate with each
other.

In other hand we can consider the work of port in connection-based communication is


like a medium through which, an application establish a connection with another
application by binding a socket by a port number. Addressing the information and the
port no., accompanied the data transfer over the network. The Ports are used by TCP
and UDP to deliver the data to the right application, are identified by a 16-bit number. It
will take effect of registering the application with the system to receive all data bound for
that port. There is a limitation for the port that no port can be bound by two applications
at the same time.

Introduction of networking Ports

In computer networking of connection-based communication port is like a medium


through which, an application establish a connection with another application by binding
a socket by a port number. Addressing the information and the port no., accompanied
the data transfer over the network. The Ports are used by TCP and UDP to deliver the
data to the right application, are identified by a 16-bit number present in the header of a
data packet. Ports are typically used to map data to a particular process running on a
client. If we consider a letter (data packet) sent to a particular apartment (IP) with
house no. (port no), at this time the port no. is the most important part for the delivery
of the letter. In order for the delivery to work, the sender needs to include an house
number along with the address to ensure the letter gets to the right destination.

If we consider the client-server architecture, a server application binds a socket to a


specific port number in connection-based communication. It registered the server with
the system where all the data destined for that port.Now we are aware of the importance
of the port number. In the same order there are some ports which are predefine and
called reserved ports. Some of them are given below :-

Reserved port numbers.

Service Port no
echo 7
daytime 13
ftp 21
telnet 23
smtp 25
finger 79
http 80
pop3 110
If we consider the range of the port numbers, there are 0 to 65,535 ports available. The
port numbers ranging from 0 - 1023 are reserved ports or we can say that are restricted
ports. All the 0 to 1023 ports are reserved for use by well-known services such as FTP,
telnet and http and other system services. These ports are called well-known ports.

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268) Page 2


Server Sockets
In common language we can say that the sockets are just like an end-point of two-way
communication link over the network between two programs. Socket classes are used to
establish a connection between client program and a server program. In java there is a
java.net package, which provides two types of classes- first is ordinary socket, which
implement the client side connection and second is server socket, which implement the
server side connection. In Java there are many socket class that is used for creating a
Server applications. ServerSockets are quite different from normal Sockets. The main
work of ServerSocket class is to wait for a request of connection by the client and
connect them on published ports and then possibly returns a result to the requester. The
SocketImpl is a common superclass of all classes that actually implement sockets. It is
used to create both client and server sockets.There are some constructors that might
throw an IOException under adverse conditions. Some of the constructors are as under:

ServerSocket(int port) Creates server socket on the specified port


with a queue length of 50.
ServerSocket(int port, int maxQueue) Creates a server socket on the specified
port with a maximum queue length of
maxQueue.
ServerSocket(int port, int maxQueue, Creates a server socket on the specified
InetAddress localAddress) port with a maximum queue length of
maxQueue. On a multihomed host,
localAddress specifies the IP address to
which this socket binds.

Reserved Sockets
Once connected, a higher-level protocol ensues, 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 e-mail, 79 is for finger, 80 is for HTTP, 119 is for
netnews—and the list goes on. It is up to each protocol to determine how a client should
interact with the port.

For example, HTTP is the protocol that web browsers and servers use to transfer
hypertext pages and images. It is quite a simple protocol for a basic page-browsing web
server. Here's how it works. When a client requests a file from an HTTP server, an action
known as a hit, it simply prints the name of the file in a special format to a predefined
port and reads back the contents of the file. The server also responds with a status code
number to tell the client whether the request can be fulfilled and why. Here's an example
of a client requesting a single file, /index.html, and the server replying that it has
successfully found the file and is sending it to the client:

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268) Page 3


Internet Addressing
Every computer on the Internet has an address. An Internet address is a number that
uniquely identifies each computer on the Net. There are 32 bits in an IP address, and
we often refer to them as a sequence of four numbers between 0 and 255 separated by
dots(.). This makes them easier to remember, because they are not randomly
assigned—they are hierarchically assigned. The first few bits define which class of
network, lettered A, B,C, D, or E, the address represents. Most Internet users are on a
class C network, since there are over two million networks in class C. The first byte of a
class C network is between 192 and 224, with the last byte actually identifying an
individual computer among the 256 allowed on a single class C network. This scheme
allows for half a billion devices to live on class C networks.
Domain Naming Service (DNS)
The Internet wouldn't be a very friendly place to navigate if everyone had to refer to
their addresses as numbers. For example, it is difficult to imagine seeing
"http://192.9.9.1/" at the bottom of an advertisement. Thankfully, a clearinghouse
exists for a parallel hierarchy of names to go with all these numbers. It is called the
Domain Naming Service (DNS). 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, describes a machine's location in a name space, from right to left. For example,
www.protech-education.com is in the COM domain (reserved for U.S. commercial
sites), it is called protech-education (after the company name), and www is the name of
the specific computer that is Protech-education's web server. www corresponds to the
rightmost number in the equivalent IP address.

InetAddress
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 we discussed earlier 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 methods getLocalHost( ), getByName( ), and getAllByName( ) can be used to
create instances 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

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.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 can't resolve the name to at least one
address.The following example prints the addresses and names of the local machine and
two well-known Internet web sites:

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268) Page 4


// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throwsUnknownHostException
{
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("protech-education.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}

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.

Applets may only establish socket connections back to the host from which the applet
was downloaded. This restriction exists because it would be dangerous for applets loaded
through a firewall to have access to any arbitrary machine. There are two kinds of TCP
sockets in Java. One is for servers, and the other is for clients. The ServerSocket class
is designed to be a "listener," which waits for clients to connect before doing anything.
The Socket class 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. Here are two constructors used to create client
sockets:

Socket(String hostName, int port)

Creates a socket connecting the local host to the


named host and port; can throw an UnknownHostException or an IOException.

Socket(InetAddress ipAddress, int port)

Creates a socket using a preexisting InetAddress


object and a port; can throw an IOException.

A socket can be examined at any time for the address and port information associated
with it, by use of the following methods:

InetAddress getInetAddress( )
Returns the InetAddress associated with the Socket object.

int getPort( )
Returns the remote port to which this Socket object is connected.
int getLocalPort( )

Returns the local port to which this Socket object is connected.

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268) Page 5


URL
The URL provides a reasonably intelligible form to uniquely identify or address
information on the Internet. URLs are everywhere; every browser uses them to identify
information on the Web. In fact, the Web is really just that same old Internet with all of
its resources addressed as URLs plus HTML. Within Java's network class library, the URL
class provides a simple, concise API to access information across the Internet using
URLs.

Format
http://www.protech-education.com/ and http://www.protech-
education.com:80/index.html. 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 to URLs that refer directly to a directory resource. Thus,
http://www.protech-education.com / is the same as http://www.protech-
education.com/index.html.

Java's URL class has several constructors, and each can throw a
MalformedURLException. One commonly used form specifies the URL with a string
that is identical to what you see displayed in a browser:

URL(String urlSpecifier)

The next two forms of the constructor allow you to break up the URL into its component
parts:
URL(String protocolName, String hostName, int port, String path)
URL(String protocolName, String hostName, String path)

Another frequently used constructor allows you to use an existing URL as a reference
context and then create a new URL from that context. Although this sounds a little
contorted, it's really quite easy and useful.

URL(URL urlObj, String urlSpecifier)

In the following example, we create a URL to Patrick Naughton's home page at Protech-
education
and then examine its properties:
// Demonstrate URL.
import java.net.*;
class URL
{
public static void main(String args[]) throws MalformedURLException
{
URL hp = new URL("http://www.protech-education.com/people/naughton/");
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());
}}

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268) Page 6


TCP/IP Server Sockets
As we mentioned earlier, Java has a different socket class that must be used for creating
server applications. The ServerSocket class is used to create servers that listen for either
local or remote client programs to connect to them on published ports. Since the Web is
driving most of the activity on the Internet, this section develops an operational web
(http) server. ServerSocket are quite different from normal Sockets. When you create a
ServerSocket, it will register itself with the system as having an interest in client
connections. The constructors for ServerSocket reflect the port number that you wish to
accept connections on and, optionally, how long you want the queue for said port to be.
The queue length tells the system how many client connections it can leave pending
before it should simply refuse connections. The default is 50. The constructors might
throw an IOException under adverse conditions. Here are the constructors:

ServerSocket (int port)


Creates server socket on the specified port with a
queue length of 50.

ServerSocket (int port, int maxQueue)


Creates a server socket on the specified port with a
maximum queue length of maxQueue.

ServerSocket (int port, int maxQueue, InetAddress localAddress)


Creates a server socket on the specified port with a maximum queue length of
maxQueue. On a multihomed host, localAddress specifies the IP address to which this
socket binds.
ServerSocket has one additional method called accept( ), which is a blocking call that
will wait for a client to initiate communications, and then return with a normal Socket
that is then used for communication with the client.

Datagrams
It provides a serialized, predictable, reliable stream of packet data. TCP includes many
complicated algorithms for dealing with congestion control on crowded networks, as well
as possible expectations about packet loss. This leads to a somewhat inefficient way to
transport data. Datagrams are bundles of information passed between machines. Once
the datagram has been released to its intended target, there is no assurance that it will
arrive or even that someone will be there to catch it. Likewise, when the datagram is
received, there is no assurance that it hasn't been damaged in transit or that whoever
sent it is still there to receive a response. Java implements datagrams on top of the UDP
protocol by using two classes: The DatagramPacket object is the data container, while
the DatagramSocket is the mechanism used to send or receive the DatagramPackets.

DatagramPacket

DatagramPackets can be created with one of four constructors. The first constructor
specifies a buffer that will receive data, and the size of a packet. It is used for receiving
data over a DatagramSocket. The second form allows you to specify an offset into the
buffer at which data will be stored. The third form specifies a target address and port,
which are used by a DatagramSocket to determine where the data in the packet will be
sent. The fourth form transmits packets beginning at the specified offset into the data.
Think of the first two forms as building an "in box," and the second two forms as stuffing
and addressing an envelope. Here are the four constructors:

DatagramPacket(byte data[ ], int size)


DatagramPacket(byte data[ ], int offset, int size)
DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)
DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268) Page 7


// URL Program

import java.net.URL;
import java.net.URLConnection;

public class MainClass {

public static void main(String args[]) throws Exception {

URL u = new URL("http://www.protech-education.com");


URLConnection uc = u.openConnection();
for (int j = 1;; j++) {
String header = uc.getHeaderField(j);
if (header == null)
break;
System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
}
}
}

//ServerSocket Example

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MainClass2 {


public static void main(String[] args) throws IOException {

int port = 49393;


ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();

String response = "Hello " + s.getInetAddress() + " on port " + s.getPort() + "\r\n";
response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort() + "\r\n";

OutputStream out = s.getOutputStream();


out.write(response.getBytes("US-ASCII"));
out.flush();
s.close();
} catch (IOException ex) {
} } }}

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268) Page 8


// TCPEchoClient Program

import java.net.*; // for Socket


import java.io.*; // for IOException and Input/OutputStream

public class TCPEchoClient {

public static void main(String[] args) throws IOException {

if ((args.length < 2) || (args.length > 3))


throw new IllegalArgumentException("Parameter(s): <Server> <Word> [<Port>]");

String server = args[0]; // Server name or IP address

byte[] byteBuffer = args[1].getBytes();

int servPort = (args.length == 3) ? Integer.parseInt(args[2]) : 7;

// Create socket that is connected to server on specified port


Socket socket = new Socket(server, servPort);
System.out.println("Connected to server...sending echo string");
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(byteBuffer); // Send the encoded string to the server
int totalBytesRcvd = 0; // Total bytes received so far
int bytesRcvd; // Bytes received in last read
while (totalBytesRcvd < byteBuffer.length) {
if ((bytesRcvd = in.read(byteBuffer, totalBytesRcvd,
byteBuffer.length - totalBytesRcvd)) == -1)
throw new SocketException("Connection close prematurely");
totalBytesRcvd += bytesRcvd;
}
System.out.println("Received: " + new String(byteBuffer));
socket.close();
}
}

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268) Page 9


Explain Proxy Server
In computer networks, a proxy server is a server (a computer system or an
application) that acts as an intermediary for requests from clients searching resources
from other servers. A client connects to the proxy server, requesting some service, such
as a file, connection, web page, or other resource available from a different server. The
proxy server evaluates the request according to its filtering rules. For example, it may
filter traffic by IP address or protocol. If the request is validated by the filter, the proxy
provides the resource by connecting to the relevant server and requesting the service on
behalf of the client. A proxy server may optionally alter the client's request or the
server's response, and sometimes it may serve the request without contacting
the specified server. In this case, it 'caches' responses from the remote server, and
returns subsequent requests for the same content directly.
The proxy concept was invented in the early days of distributed systems as a way to
simplify and control their complexity. Today, most proxies are a web proxy, allowing
access to content on the World Wide Web.

Proxy servers have two main purposes:


 Improve Performance: Proxy servers can significantly improve performance for
groups of users. This is because it saves the results of all requests for a certain
amount of time. Consider the case where both user X and user Y access
the World Wide Web through a proxy server. First user X requests a certain Web
page, which we'll call Page 1. Sometime later, user Y requests the same page.
Instead of forwarding the request to the Web server where Page 1 resides, which
can be a time-consuming operation, the proxy server simply returns the Page 1
that it already fetched for user X. Since the proxy server is often on the
same network as the user, this is a much faster operation. Real proxy servers
support hundreds or thousands of users. The major online services such
as America Online, MSN and Yahoo, for example, employ an array of proxy
servers.
 Filter Requests: Proxy servers can also be used to filter requests. For example,
a company might use a proxy server to prevent its employees from accessing a
specific set of Web sites

PROTECH COMPUTER EDUCATION (Rahul Sir’ Classes – 9960086068/9823112268)Page 10

You might also like