0% found this document useful (0 votes)
90 views

Java Networking PDF

The document discusses Java networking concepts including network basics, sockets, ports, proxy servers, URL addressing, Java networking classes and interfaces, implementing TCP/IP client-server applications, and datagrams. It provides details on sockets, ports, TCP vs UDP, forward and reverse proxy servers, the URL class and connections, and common Java networking classes.

Uploaded by

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

Java Networking PDF

The document discusses Java networking concepts including network basics, sockets, ports, proxy servers, URL addressing, Java networking classes and interfaces, implementing TCP/IP client-server applications, and datagrams. It provides details on sockets, ports, TCP vs UDP, forward and reverse proxy servers, the URL class and connections, and common Java networking classes.

Uploaded by

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

Networking with Java – 6 hr

1. Networking basics
2. Sockets, port
3. Proxy servers
4. Internet addressing URL
5. java.net – Networking classes and Interfaces
6. Implementing TCP/IP based Server and Client
7. Datagrams – Datagram packet, Datagram server and client
8. URL connections
Networking basics:
Networking is a concept of connecting two or more computing
devices together so that we can share resources.

To share date there should be different type of protocol to be


followed.

Network programming refers to writing programs that executes


across multiple device in which the device are connected to each
other using network.

The java.net package contains a collection of classes and


interface that provides the low-level communication.
The Java.net package provides support for two common networks
protocols

TCP (Transmission Control Protocol) – Reliable communication and


connection oriented
UDP (User Datagram Protocol) – Connection less protocol that allows
for packet of data to be transmitted between applications.
Port: Client Connect to server through object known a ports
Ports numbers are port of addressing information used to identify the
senders and receivers of the message.

They are associated with TCP/IP network connection and might be


described as a sort of add-on to the IP address

Port numbers allow different applications on the same computer to


share network resources simultaneously.

It is a 16 bits value (0-65535)


0-1023 : Well Defined Protocol.
1024-49151 : Reserve by company for their product
Unique id of protocols in computer network
Socket and Ports
Socket is communication between two computers using TCP.

A socket is bound to a port number so that the TCP layer can identify
the application that data is destined to be sent to

Socket is combination of IP and Port


32+16 = 48 bit

Sockets are created and used with a set of programming request or


socket API
There are two types of programming in socket programming
Client Side Programming
Server Side Programming.
• A client program creates a socket on its end of the communication and
attempts to connect that socket to server.
• When a connection is made, the server creates a socket objet on its end of
communication. The client and server now communicate by writing to and
reading from socket

• There are following procedure on socket programming.


– Server Sequence of Sockets
• Socket()
• Bind()
• Recvfrom()
• Sendto()

– Client Sequence of Sockets


• Socket()
• Connect()
• Send()
• Recv()
Flow of server/client Application
• The server socket is established. With constructor ServerSocket()

• The server is listening on port on incoming connections(blocking wait).


Once it unblocks, the connection request that unblocked it is stored inside a
Socket.

• The client sends a message to the server via a Socket, which the server
immediately stores when it unblocks.

• The server wakes up because it got a message (unblocks), and the Socket
connection is established.

• The server reads the message from the client. (If you skip this step, the
client typically gets confused). This is done via the Socket accepted.

• The server generates a response to the client and sends it, through a write
stream of the Socket accepted.

• The server closes the output stream(of the Socket accepted) to indicate end
of communication. (This is required).
Socket() To create a socket

It’s a socket identification like a telephone number to


Bind()
contact

Listen() Ready to receive a connection

Connect() Ready to act as a sender

Confirmation, it is like accepting to receive a call from a


Accept()
sender

Write() To send data

Read() To receive data

Close() To close a connection


Proxy Server
• It is an intermediary server between client and internet
• It offer following services
– Firewall and network data filtering
– Network connection sharing
– Data Caching

Following are purpose of using proxy servers


– Monitoring and filtering (Content Filtering)
– Improving Performance
• It makes service faster by process of retrieving content from
the cache which was saved when previous request was made
by client.
– Accessing services Anonymously
• In this the destination server receives the request from the
anonym zing proxy server and does not receive information
about end user
Types of Proxy Server

Forward Proxy Server


• It sits between clients and the internet to establish a connection with
the internet on behalf of the clients

• To prevent direct communication between the client’s computer and


the target website, a forward proxy server receives requests from
clients and forwards them to the target site, which then receives the
provided information from the target site and forwards it to the
client.

• Forward proxies can also be anonymous proxies and allow users to


hide their IP address while browsing the Web or using other Internet
services.
Forward Proxy Server
Reverse proxy
• A client sends the connection request to the internet.
• Instead of connecting the client directly to the web server, the
internet forwards the client’s connection request to a reverse proxy.
• The reverse proxy communicates with the web server.
• The web server provides the requested information to the reverse
proxy.
• The response from the origin server is received by the reverse proxy
and sent to the client.
Reverse proxy
Internet Addressing URL

• URL class is the gateway to any of the resource available on


internet. A class URL represents a Uniform Resource Locator which
is a pointer to resource on www
• https://lagrandee.edu.np/faculty.php
• Protocol: Here https is protocol
• Host Name : Here lagrandee.edu.np is server name.
• File Name: Here faculty.php is the file Name.
Commonly Used method of Java URL class

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.

public String getAuthority() it returns the authority of the URL. (Host


Name with define port number)
• //URLDemo.java
import java.net.*;
public class UrlClass{
public static void main(String[] args){
try{
URL url=new
URL("https://www.lagrandee.edu.np:10/faculty-and-staff/");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
System.out.println(“Authority Name: "+url.getAuthority());

}catch(Exception e){System.out.println(e);}
}
OUTPUTTTTTTTTTTTTTTT
} Protocol: https
Host Name: www.lagrandee.edu.np
Port Number: 10
File Name: /faculty-and-staff/
Java URL connection class:

• Java URL connection class represents a communication link the


URL and the application.
• This class can be used to read and write data to specified resource
referred by the URL
• The openConnection() method of the URL class returns the object of
URLConnection class.
import java.io.*;
import java.net.*;
public class UrlConnection {
public static void main(String[] args){
try{
URL url=new URL("https://www.lagrandee.edu.np/faculty-and-
staff/");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}
Java.net- Networking classes and Interface
• Java is premier language for network programming. Java support
UDP and TCP
• TCP is use for reliable stream based I/O across the network
• UDP support simpler, faster, point-to-point datagram oriented
mode. It encapsulate the large numbers of class and interface that
provides a easy to use means to access network resources.

Some Classes and interface of java.net package.


Classes in Java.net Package
• URLConnection: This class can be used to read and write data to specified
resource referred by the URL

• CacheRequest – The CacheRequest class is used whenever there is


a need to store resources in ResponseCache. The objects of this class
provide an edge for the OutputStream object to store resource data
into the cache

• CookieHandler – To implement a callback mechanism for securing


up an HTTP state management policy implementation inside the
HTTP protocol handler. The HTTP state management mechanism
specifies the mechanism of how to make HTTP requests and
responses.

• CookieManager – This class separates the storage of cookies from


the policy surrounding accepting and rejecting cookies. A
CookieManager comprises a CookieStore and a CookiePolicy.
• DatagramPacket – The DatagramPacket class is used to provide a
facility for the connectionless transfer of messages from one system
to another.

• InetAddress – The InetAddress class is used to provide methods to


get the IP address of any hostname.

• Server Socket – The ServerSocket class is used for implementing


system-independent implementation of the server-side of a
client/server Socket Connection. The constructor for ServerSocket
class throws an exception if it can’t listen on the specified port. For
example – it will throw an exception if the port is already being
used.
• Socket – The Socket class is used to create socket objects that help
the users in implementing all fundamental socket operations. Such
as sending, reading data, and closing connections.

• DatagramSocket – The DatagramSocket class is a network socket


that provides a connection-less point for sending and receiving
packets. Every packet sent from a datagram socket is individually
routed and delivered. It can further be practiced for transmitting and
accepting broadcast information. Datagram Sockets is Java’s
mechanism for providing network communication via UDP instead
of TCP.

• URL – The URL class in Java is the entry point to any available
sources on the internet. A Class URL describes a Uniform Resource
Locator, which is a signal to a “resource” on the World Wide Web. A
source can denote a simple file or directory, or it can indicate a more
difficult object, such as a query to a database or a search engine.
Interfaces in Java.net
• CookiePolicy – The CookiePolicy interface in the java.net package
provides the classes for implementing various networking applications. It
decides which cookies should be accepted and which should be rejected.
In CookiePolicy, there are three pre-defined policy implementations,
namely ACCEPT_ALL, ACCEPT_NONE, and
ACCEPT_ORIGINAL_SERVER.

• CookieStore – A CookieStore is an interface that describes a storage


space for cookies. CookieManager combines the cookies to the
CookieStore for each HTTP response and recovers cookies from the
CookieStore for each HTTP request.

• FileNameMap – The FileNameMap interface is an uncomplicated


interface that implements a tool to outline a file name and a MIME type
string. FileNameMap charges a filename map ( known as a mimetable)
from a data file.
• SocketOption – The SocketOption interface helps the users to control
the behavior of sockets. Often, it is essential to develop necessary
features in Sockets. SocketOptions allows the user to set various standard
options.

• SocketImplFactory – The SocketImplFactory interface defines a factory
for SocketImpl instances. It is used by the socket class to create socket
implementations that implement various policies.

• ProtocolFamily – This interface represents a family of communication


protocols. The ProtocolFamily interface contains a method known as
name(), which returns the name of the protocol family.
Implementing TCP/IP based Server and Client

Steps in Establishing a TCP connection using Socket

• Get connected with server using ServerSocket class object having


Port number.
• Accept() method of ServerSocket class wait unit client socket get
ready.
• Client create Socket Object with Server name and port number.
• If port number of client and server get match then there establish
connection.
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream (s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream (s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Datagrams – Datagram packet, Datagram server and client
• Java DatagramSocket and DatagramPacket classes are used for
connection-less socket programming using the UDP instead of TCP.

Datagrams
• Datagrams are collection of information sent from one device to
another device via the established network. When the datagram is
sent to the targeted device, there is no assurance that it will reach to
the target device safely and completely. It may get damaged or lost
in between. Likewise, the receiving device also never know if the
datagram received is damaged or not. The UDP protocol is used to
implement the datagrams in Java.
• DatagramPacket is a message that can be sent or received. It is a
data container. If you send multiple packet, it may arrive in any
order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class

• DatagramPacket(byte[] barr, int length): it creates a datagram


packet. This constructor is used to receive the packets.
• DatagramPacket(byte[] barr, int length, InetAddress address,
int port): it creates a datagram packet. This constructor is used to
send the packets.

• InetAddress : Ip Address of any HostName.


• DatagramSocket class is the mechanism used to establish the
communications using UDP protocol.

• The DatagramSocket class represents a connection less socket for


sending and receiving the data packets.

Commonly used Constructors of DatagramSocket class


• DatagramSocket() throws SocketEeption: it creates a datagram
socket and binds it with the available Port Number on the localhost
machine.

• DatagramSocket(int port) throws SocketEeption: it creates a


datagram socket and binds it with the given Port Number.

• DatagramSocket(int port, InetAddress address) throws


SocketEeption: it creates a datagram socket and binds it with the
specified port number and host address.
// DataGram Sender File Code

import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip,3000);
ds.send(dp);
ds.close();
}
}
// DataGram Receiver File Code

import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}

You might also like