0% found this document useful (0 votes)
17 views43 pages

Chapter4 - AJP

Chapter 04 covers networking basics, including the use of sockets for client/server communication, the differences between IP addresses and port numbers, and the TCP and UDP protocols. It explains how to use the InetAddress and URLConnection classes in Java, as well as the methods and constructors of the Socket and ServerSocket classes for establishing connections. Additionally, it introduces DatagramSockets for UDP communication and provides examples of client and server implementations.

Uploaded by

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

Chapter4 - AJP

Chapter 04 covers networking basics, including the use of sockets for client/server communication, the differences between IP addresses and port numbers, and the TCP and UDP protocols. It explains how to use the InetAddress and URLConnection classes in Java, as well as the methods and constructors of the Socket and ServerSocket classes for establishing connections. Additionally, it introduces DatagramSockets for UDP communication and provides examples of client and server implementations.

Uploaded by

dabin40235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

Chapter 04

Networking Basics
Outcomes :-

1) Use Inet Address class to know the IP address of the given


host name
2) Use URLConnection class to read and write data to the
specified resources referred by the given URL.
3) Develop program for Client/Server communication through
TCP/IP Server Sockets for the given problem.
4) Write program to illustrate the client server communication
using datagram protocol for the given problem.
Basics of Networking
What Is a Socket?

-> A socket is one end-point of a two-way communication


link between two programs running on the network.
-> Socket classes are used to represent the connection
between a client program and a server program.
-> The java.net package provides two classes, Socket and
ServerSocket that implement the client side of the
connection and the server side of the connection,
respectively.
-> The client in socket programming must know two
information:
1) IP Address of Server, and
2) Port number.
What Is Port Number?
-> A port number is the logical address of each application or
process that uses a network or the Internet to communicate.
-> It uniquely identifies a network-based application on a
computer.
-> Each application / program is allocated a 16-bit integer
port number. This number is assigned automatically by the
OS, manually by the user or is set as a default for some
popular applications.
-> Port nos from 1-1023 are reserved, we can use port nos
from 1024-65535.
-> For example : Port Number 80 for HTTP, 23 for Telnet and
25 for SMTP.
Difference between IP address and Port Number
SERI IP ADDRESS PORT NUMBER
AL
NO

01 Internet Protocol address (IP Port number is used to identify an


address) used to identify a host in processes/services on your system
network.

02 IPv4 is of 32 bits (4 bytes) size and The Port number is 16 bits numbers.
for IPv6 is 128 bits (16 bytes).

03 IP address is the address of the layer- Port number is the address of the layer-
3 IP protocol 4 protocols.
06
04 IP address is provided by admin of Port number for application is provided
system or network administrator. by kernel of Operating System.
05 ipconfig command can be used to netstat command can be used to find
find IP address . Network Statistics Including Available
TCP Ports

06 192.168.0.2, 172.16.0.2 are some of 80 for HTTP, 123 for NTP, 67 and 68 for
IP address examples. DHCP traffic, 22 for SSH, 25 for SMTP
etc.
TCP & UDP Protocols

• TCP − TCP stands for Transmission Control


Protocol, which allows for reliable
communication between two applications.
TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
• UDP − UDP stands for User Datagram Protocol,
a connection-less protocol that allows for
packets of data to be transmitted between
applications.
Proxy Server
• A proxy server is a computer that offers a
computer network service to allow clients to
make indirect network connections to other
network services.
• A client connects to the proxy server, then
requests a connection, file, or other resource
available on a different server.
• The proxy provides the resource either by
connecting to the specified server or by serving
it from a cache
Proxy Server
Internet Addressing

Java InetAddress class


-> Java InetAddress class is java’s representation of an IP address.
-> It is a combination of IP address and Host name.
-> The java.net.InetAddress class provides methods to get the IP of any
host name for example www.javatpoint.com, www.google.com,
www.facebook.com etc.

-> Factory Methods of InetAddress class


• As we know, "new" Keyword is used to create object to that
corresponding class.
• But, In the InetAddress Class has no visible constructors. to create a
InetAddress object, we use Factory Method to create objects. ( Factory
Method is a static method in a class return an instance of that class).
• Three 3 commonly used InetAddress factory methods are:
Inet address class Methods
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args)
{
try
{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
for (int i=0; i<SW.length; i++)
{
System.out.println(SW[i]);
}
}
catch(Exception e){System.out.println(e);
}
}
} Output :
Host Name: www.javatpoint.com
IP Address: 206.51.231.148
www.nba.com/23.15.35.11
www.nba.com/23.15.35.18
Instance Methods

• The InetAddress class also has several other methods, which


can be used on the objects returned by the Factory methods
Method Description
boolean equals(Object other) Returns true if this object has the same Internet
address as other.
byte[ ] getAddress( ) Returns a byte array that represents the object’s
Internet address in network byte order.
String getHostAddress( ) Returns a string that represents the host address
associated with the InetAddress object.
String getHostName( ) Returns a string that represents the host name
associated with the InetAddress object.
boolean isMulticastAddress( ) Returns true if this Internet address is a multicast
address. Otherwise, it returns false.
String toString( ) Returns a string that lists the host name and the
IP address
Java Socket Programming or Network
Programming
• Sockets provide the communication mechanism
between two computers using TCP. A client program
creates a socket on its end of the communication and
attempts to connect that socket to a server.
• When the connection is made, the server creates a
socket object on its end of the communication. The
client and the server can now communicate by writing
to and reading from the socket.
• The java.net.Socket class represents a socket, and the
java.net.ServerSocket class provides a mechanism for
the server program to listen for clients and establish
connections with them.
Steps occur when establishing a TCP connection
between two computers using sockets
1) The server instantiates a ServerSocket object, denoting
which port number communication is to occur on.
2) The server invokes the accept() method of the ServerSocket
class. This method waits until a client connects to the server on
the given port.
3) After the server is waiting, a client instantiates a Socket
object, specifying the server name and the port number to
connect to.
4)The constructor of the Socket class attempts to connect the
client to the specified server and the port number. If
communication is established, the client now has a Socket
object capable of communicating with the server.
5) On the server side, the accept() method returns a reference
to a new socket on the server that is connected to the client's
socket.
TCP connection between two computers using sockets

• After the connections are established,


communication can occur using I/O streams.
• Each socket has both an OutputStream and an
InputStream. The client's OutputStream is
connected to the server's InputStream, and the
client's InputStream is connected to the server's
OutputStream.
• TCP is a two-way communication protocol
hence data can be sent across both streams at
the same time.
ServerSocket Class Constructors
The java.net.ServerSocket class is used by server applications to obtain a port
and listen for client requests.
The ServerSocket class has four constructors

1) public ServerSocket(int port) throws IOException


Attempts to create a server socket bound to the specified port. An exception
occurs if the port is already bound by another application.
2) public ServerSocket(int port, int backlog) throws IOException
Similar to the previous constructor, the backlog parameter specifies how many
incoming clients to store in a wait queue.
3) public ServerSocket(int port, int backlog, InetAddress address) throws
IOException
Similar to the previous constructor, the InetAddress parameter specifies the
local IP address to bind to. The InetAddress is used for servers that may have
multiple IP addresses, allowing the server to specify which of its IP addresses to
accept client requests on.
4) public ServerSocket() throws IOException
Creates an unbound server socket. When using this constructor, use the bind()
method when you are ready to bind the server socket.
ServerSocket Class Methods

1) public int getLocalPort()


Returns the port that the server socket is listening on.
2) public Socket accept() throws IOException
Waits for an incoming client. This method blocks until either a client connects to
the server on the specified port or the socket times out, assuming that the
time-out value has been set using the setSoTimeout() method. Otherwise, this
method blocks indefinitely.
3)public void setSoTimeout(int timeout)
Sets the time-out value for how long the server socket waits for a client during
the accept().
4) public void bind(SocketAddress host, int backlog)
Binds the socket to the specified server and port in the SocketAddress object.
This method is used when ServerSocket is instantiated using the no-argument
constructor.
Socket Class Constructors

1) public Socket(String host, int port) throws UnknownHostException, IOException.


This constructor attempts to connect to the specified server at the specified port. If
it does not throw an exception, the connection is successful and the client is
connected to the server.
2) public Socket(InetAddress host, int port) throws IOException
This constructor is identical to the previous constructor, except that the host is
denoted by an InetAddress object.
3) public Socket(String host, int port, InetAddress localAddress, int localPort)
throws IOException.
Connects to the specified host and port, creating a socket on the local host at the
specified address and port.
4) public Socket(InetAddress host, int port, InetAddress localAddress, int localPort)
throws IOException.
This constructor is identical to the previous constructor, except that the host is
denoted by an InetAddress object instead of a String.
5)public Socket()
Creates an unconnected socket. Use the connect() method to connect this socket to
a server.
Socket Class Methods

1) public void connect(SocketAddress host, int timeout) throws


IOException
This method connects the socket to the specified host. This method is
needed only when you instantiate the Socket using the no-argument
constructor.

2) public InetAddress getInetAddress()


This method returns the address of the other computer that this socket is
connected to.

3)public int getPort()


Returns the port the socket is bound to on the remote machine.

4) public int getLocalPort()


Returns the port the socket is bound to on the local machine.
Socket Class Methods
5) public SocketAddress getRemoteSocketAddress()
Returns the address of the remote socket.

6) public InputStream getInputStream() throws IOException


Returns the input stream of the socket. The input stream is connected to the output
stream of the remote socket.

7)public OutputStream getOutputStream() throws IOException


Returns the output stream of the socket. The output stream is connected to the input
stream of the remote socket.

8) public void close() throws IOException


Closes the socket, which makes this Socket object no longer capable of connecting again
to any server.

[IMP :- readUTF and writeUTF are methods used to read and write data on Input stream
and Output stream respectively.]
[ PrintStream is a class which provides methods to write data to another stream]
[ipconfig method is used to find ip address of server.]
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);
}
}
}
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.net.*;
import java.util.Scanner;
import java.io.*;
public class client
{
public static void main(String args[])throws IOException
{
int number,temp;
Scanner sc= new Scanner(System.in);
Socket s=new Socket("10.2.1.45",1342);
Scanner sc1=new Scanner(s.getInputStream());
System.out.println("Enter any number");
number=sc.nextInt();
PrintStream p=new PrintStream(s.getOutputStream());
p.println(number);
temp = sc1.nextInt();
System.out.println(temp);
}
}
import java.net.*;
import java.util.Scanner;
import java.io.*;
public class server
{
public static void main(String args[]) throws IOException
{
int number,temp;
ServerSocket s1=new ServerSocket(1342);
Socket ss=s1.accept();
Scanner sc=new Scanner(ss.getInputStream());
number=sc.nextInt();
temp=number*2;
PrintStream p=new PrintStream(ss.getOutputStream()); //The PrintStream class
provides methods to write data to another stream.
p.println(temp);
}
}
UDP Programming

• DatagramSockets are Java’s mechanism for


network communication via UDP instead of
TCP.
• Java provides DatagramSocket to communicate
over UDP instead of TCP. It is also built on top
of IP. DatagramSockets can be used to both
send and receive packets over the Internet.
• One of the examples where UDP is preferred
over TCP is the live coverage of TV channels. In
this aspect, we want to transmit as many
frames to live audience as possible not
worrying about the loss of one or two frames.
UDP Programming
• DatagramPacket and DatagramSocket are
the two main classes that are used to
implement a UDP client/server application.
• In UDP’s terms, data transferred is
encapsulated in a unit called datagram.
• A datagram is an independent, self-
contained message sent over the network
whose arrival, arrival time, and content are
not guaranteed.
• In Java, DatagramPacket represents a
datagram.
Datagram Packet constructors

• You can create a DatagramPacket object by using


one of the following constructors:
1) DatagramPacket(byte[] buf, int length)
2) DatagramPacket(byte[] buf, int length,
InetAddress address, int port)
• Here, the data must be in the form of an array of
bytes. The first constructor is used to create
a DatagramPacket to be received.
• The second constructor creates
a DatagramPacket to be sent, so we need to
specify the address and port number of the
destination host.
• The parameter length specifies the amount of data
in the byte array to be used, usually is the length
of the array (buf.length).
DatagramSocket constructors

• DatagramSocket is used to send and


receive DatagramPackets.
• DatagramSocket represents a UDP connection between two
computers in a network.
• In Java, we use DatagramSocket for both client and server.
There are no separate classes for client and server like TCP
sockets.
• To create a DatagramSocket object to establish a UDP
connection for sending and receiving datagram, following
constructors can be used.
DatagramSocket constructors
1) DatagramSocket()
This constructor is used to create a client that binds to an
arbitrary port number.
2) DatagramSocket(int port)
This constructor is used to create a server that binds to the
specific port number, so the clients know how to connect to.
3) DatagramSocket(int port, InetAddress addr)
This constructor binds the server to the specified IP address (in
case the computer has multiple IP addresses).
• These constructors can throw SocketException if the socket
could not be opened, or the socket could not bind to the
specified port or address
Methods of DatagramSocket
1) send(DatagramPacket p):
sends a datagram packet.
2) receive(DatagramPacket p):
receives a datagram packet.
3) setSoTimeout(int timeout):
sets timeout in milliseconds, limiting the
waiting time when receiving data. If the timeout
expires, a SocketTimeoutException is raised.
4) close():
closes the socket.
• These methods can
throw IOException , PortUnreachableException ,
SocketTimeoutException
Example using UDP connection
import java.io.*;
import java.net.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPClient
{
public static void main(String args[])throws Exception
{
DatagramSocket ds=new DatagramSocket();
int i=8;
byte[] b=String.valueOf(i).getBytes();
InetAddress ia= InetAddress.getLocalHost();
DatagramPacket dp= new DatagramPacket(b,b.length,ia,9999);
ds.send(dp);
byte[] b1=new byte[1024];
DatagramPacket dp1= new DatagramPacket(b1, b1.length);
ds.receive(dp1);
String str=new String(dp1.getData(),0,dp1.getLength());
System.out.println("Result is " + str);
}
}
import java.io.*;
import java.net.*;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class UDPServer
{
public static void main(String args[])throws Exception
{
DatagramSocket ds=new DatagramSocket(9999);
byte[] b1= new byte[1024];
DatagramPacket dp=new DatagramPacket(b1,b1.length);
ds.receive(dp);
String str=new String(dp.getData(),0,dp.getLength());
int num= Integer.parseInt(str.trim());
int result=num*num;
byte[] b2=String.valueOf(result).getBytes();
InetAddress ia= InetAddress.getLocalHost();
DatagramPacket dp1=new DatagramPacket(b2,b2.length,ia,dp.getPort());
ds.send(dp1);
}
}
URL class in Java

-> Hierarchy of classes


-> Methods of the class
-> Examples using the class
Hierarchy of Classes

DatagramPacket

DatagramSocket

InetAddress
Object
Socket

ServerSocket

URL

URLConnection
URL class

• URL stands for Uniform Resource Locator


• It is a description of resource location on the Internet.
• Java provides a class java.net.URL to manipulate URLs.
• For example :- http://www.javapoint.com/URL-class
• A URL contains many information:
1) Protocol: Here http is the protocol.
2) Server name or IP Address: Here, www.javatpoint.com is the
server name.
3) Port Number: It is an optional attribute. If we write
http//www.javatpoint.com:80/URL-class, 80 is the port number.
If port number is not mentioned in the URL, it returns -1.
4) File Name or directory name: In this case, URL-class is the file
name.
URL class Constructors
1) public URL(String protocol, String host, int port, String file)
throws MalformedURLException
Creates a URL by putting together the given parts.

2) public URL(String protocol, String host, String file) throws


MalformedURLException
Identical to the previous constructor, except that the default port
for the given protocol is used.

3) public URL(String url) throws MalformedURLException


Creates a URL from the given String.
URL class Methods
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 URLConnection It returns the instance of


openConnection() URLConnection i.e. associated with
this URL.
URL class example
import java.io.*;
import java.net.*;
public class URLDemo
{
public static void main(String[] args)
{
try
{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
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());
}
catch(Exception e)
{
System.out.println(e);
}
}
}
URLConnection class in Java
• The Java URLConnection class represents a
communication link between the URL and the
application.
• This class can be used to read and write data to the
specified resource referred by the URL.
• To create object of URLConnection class the
openConnection() method of URL class is used.
• Syntax:public URLConnection openConnection()throws I
OException
• getInputStream() method is used to display all the data
of a webpage. It returns all the data of the specified URL
in the stream that can be read and displayed.
Displaying source code of a webpage by
URLConnecton class
import java.io.*;
import java.net.*;
public class URLConnectionDemo
{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/URLConnection-class");
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);}
}
}

You might also like