0% found this document useful (0 votes)
11 views16 pages

UNIT 5 Basic Networking

The document provides an overview of Java networking, focusing on socket programming, client-server architecture, and internet addressing. It explains the concepts of sockets, protocols, IP addresses, and the use of classes like InetAddress, URL, and URLConnection in Java. Additionally, it covers TCP/IP and UDP communication through examples of client-server and datagram socket implementations.
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)
11 views16 pages

UNIT 5 Basic Networking

The document provides an overview of Java networking, focusing on socket programming, client-server architecture, and internet addressing. It explains the concepts of sockets, protocols, IP addresses, and the use of classes like InetAddress, URL, and URLConnection in Java. Additionally, it covers TCP/IP and UDP communication through examples of client-server and datagram socket implementations.
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

UNIT-V Basics of Network Programming

Java Net Working -Java Networking is a concept of connecting two or


more computing devices together so that we can share resources.
-Java socket programming provides facility to share data between
different computing devices. -Advantages of Java Networking: -
1) Share Resources.
2)Centralize software Management.
What is Socket? -In Java, a Socket is a fundamental concept for
enabling communication between applications over a network.
-Sockets provide a mechanism for data exchange between programs
running on different machines (or the same machine) over a
network.
-Java provides a rich set of libraries in the [Link] package to work
with sockets.
-A socket is an endpoint for communication between two machines
or processes on a network. It provides a way to send and receive data
over a network.
There are two types of sockets in Java:
Client Socket: Initiates the connection to the server. Server Socket:
Listens for incoming client connections and handles the
communication.
Client-Server -The client sends requests to the server to access
services, like retrieving data or performing actions.
-The server listens for requests, processes them, and sends back the
appropriate response.
-The server provides services or resources, and the client accesses
those services.
-Client Work: The client creates a Socket to connect to the server. The
client sends a request(such as a message or data) to the server.
The client waits for the response. The client receives the response
and processes it.
-Server Work
The server listens for incoming connections using a Server Socket.
Once a client sends a request, the server accepts the connection.
The server processes the request.
The server sends the response back to the client. Reserved Socket: -
In Java, "reserved sockets" refers to socket resources that are
connected to a specific port and address in the operating system. -
These sockets can either be used for client-server communication or
other network protocols.
-When you refer to "reserved sockets," you might be referring to
reserved ports that are typically used for specific applications or
services.
-These ports are managed by the operating system and all are
predefined.
-The port number 0 to 1023are reserved ports.
-For example, HTTP (Hyper Text Transfer Protocol) use port 80, FTP
(File Transfer Protocol) use port 21, and so on.
Internet addressing:
-Internet addressing is the system used to assign unique identifiers to
devices or services connected to the internet.
-These addresses ensure that data sent over the internet reaches the
correct destination.
-There are two main types of internet addresses:
[Link] Address ((Internet Protocol Address) -The IP address is a
numerical number assigned to each device connected to a computer
network that uses the Internet Protocol for communication.
-IP Address is a unique number assigned to the computer over the
network.
-There are two versions of IP addresses i.e IPv4 & IPv6
-IP Address Classes:
Class A: 0 to 127
Class B: 128 to 191
Class C: 192 to 223
Class D: 224 to 239
Class E: 240 to 255
[Link] Name System (DNS):
-The Domain Name System (DNS) translates human-readable domain
names (e.g., [Link]) into machine-readable IP addresses
(e.g., [Link]).
-It enables computers to locate and communicate with each other on
the internet.
-It acts like a phonebook, mapping domain names to their respective
IP addresses.
-It allows users to use easy-to-remember names instead of numerical
IP addresses.
Protocol:
-A Protocol is a set of rules basically this is followed for the
communication
-For Example: - I)TCP II)FTP III)Telnet IV)SMTP V)HTTP
Port Number:
-The Port Number is used to uniquely Identify different application. -
It acts as a Communication endpoint between application.
-The port number is associated with the IP address for
communication between two applications.
-Port is a number socket on a Particular machine.
InetAddress: -In Java, InetAddressis a class in the [Link] package
that represents an Internet Protocol (IP) address
-InetAddress stands for Internet Address
-InetAddress is a combination of IP address and Host Name.
Factory Method
-Factory methods are static methods that are used to obtain
instances of the InetAddress class.
1) static InetAddress getLocalHost()
2) static InetAddress getByName(String hot_name)
3) static InetAddress getAllByName(String hot_name)
4) static InetAddress getByAddress(String IP_Address)
-All these three methods will throws UnKnownHostException
Instance Method
1) boolean equals(object obj)
2) byte[] getAddress()
3) String getHostAddress()
4) String getHostName()
5) String toString()
6) boolean isMulticastAddress()
Example:
import [Link].*;
class InetAddressDemo
{
public static void main(String args[])throws UnknownHostException
{
InetAddress addr=[Link]();
[Link](addr);
addr=[Link]("[Link]");
[Link](addr);
[Link]("Is Multicast
Addresss:"+[Link]());
InetAddress addr1[]=[Link]("[Link]");
for(int i=0;i<[Link];i++)
{
[Link](addr1[i]);
}
}
}
URL Class:
-In Java, the URL class is part of the [Link] package and represents a
Uniform Resource Locator (URL), which is a pointer to a resource on
the World Wide Web.
-The URL class allow you to manipulate and perform operations on
URLs, such as extracting components (protocol, host, path, etc.),
opening connections to the resource, and retrieving data from the
URL.
A URL typically consists of the following components:
-Protocol: Specifies the protocol (e.g., http, https, ftp).
-Host: Specifies the domain name or IP address of the server.
-Port: The port number.
-Path: Specifies the location of the resource on the server.
-Syntax: - Protocol://hostnameorIPaddress:portno/filepath
-Example:
- [Link]
-Constructors:
1) URL(String urlstring)
2) URL(String protocolName, String HostName, int port, String
filepath);
3) URL(String protocolName, String HostName,String filepath);
-Methods: 1) String getProtocol(); 2) int getPort(); 3) String getHost();
4) String getFile();
-Example:
import [Link].*;
class URLDemo
{
public static void main(String args[])throws MalformedURLException
{
URL u1=new URL("[Link]
[Link]("Protocol Name:"+[Link]());
[Link]("Host Name:"+[Link]());
[Link]("Port No:"+[Link]());
[Link]("File Path:"+[Link]());
}
}
OUTPUT:
Protocol Name:https
Host Name:[Link]
Port No:80 File Path:/[Link]
URLConnection Class:
-It is used to access attributes of remote resources.
-The URLConnectionclass in Java is part of the [Link] package and
provides a way to interact with URLs.
-The URLConnection class is used to establish a connection to a URL,
and it is used when you need to perform I/O operations on a
resource
-URLConnection is protocol-independent, so it can be used for
different types of URLs, like HTTP, FTP, file paths, etc.
-You can set request headers, read response headers, and get
information about the content type and encoding using this class.
-The class provides methods to get input and output streams to read
and write data to the URL.
Methods: 1) int getContentLength() 2) String getContentType() 3)
long getDate() 4) long getlastModified() 5) long getExpiration() 6)
InputStream getInputStream()
Example:
import [Link].*;
import [Link].*;
import [Link].*;
class URLConnectionDemo
{
public static void main(String
args[])throwsMalformedURLException,IOException

{
URL u1=new URL("[Link]
URLConnection u2=[Link]();
[Link]("Content Type:"+[Link]());
[Link]("Content Length:"+[Link]());
[Link]("Today Date:"+new Date([Link]()));
[Link]("Expiration Date:"+new Date([Link]()));
[Link]("Last Modified Date:"+new
Date([Link]()));
}
}
OUTPUT:
Content Type:text/html;
charset="utf-8"
Content Length:-1
Today Date:Sat Mar 15 07:46:31 IST 2025
Expiration Date:Sat Jan 01 05:30:00 IST 2000
Last Modified Date:Thu Jan 01 05:30:00 IST 1970
TCP/IP Client and Server Sockets:
-In Java, TCP/IP communication can be implemented using sockets.
The Java [Link] package provides classes for networking, including
Socketfor the client-side and ServerSocket for the server-side.
-ServerSocket and Socket both are predefined classes which are
present under [Link] package
-The client connects to the server's IP address and port, sends data,
and waits for a response.
-The server will listen on a specific port for incoming connections
from clients, then accept those connections to communicate.
Socket Class:
-Constructors: oSocket(String HostName,int port)
oSocket(InetAddress addr,int port)
-Methods:
oInetAddress getInetAddress();
oint getPort();
oint getLocalPort();
oInputStream getInputStream()
oOutputStream getOutputStream()
ovoid close()
ServerSocket Class:
-Constructors:
oServerSocket(int port) oServerSocket(int port , int maxqueue)
oServerSocket(int port,int maxqueue,InetAddress addr); -Methods:
oaccept();
Example:
//Client Program
import [Link].*;
import [Link].*;
class Client
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",9090);
InputStream in=[Link]();
OutputStream out=[Link]();
byte str[]="Hi Server".
getBytes();
[Link](str);
[Link]();
}
}
//Server Program
import [Link].*;
import [Link].*;
class Server
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(9090);
Socket s1=[Link]();
InputStream in=[Link]();
OutputStream out=[Link]();
int c;
while((c=[Link]())!=-1)
{
[Link]((char)c);
} [Link]();
}
}
Program:
Chat Application using TCP/IP Client and Server Sockets.
Client Program
import [Link].*;
import [Link].*;
class ClientChatApp
{
public static void main(String args[])throws IOException
{
Socket s=new Socket("localhost",9090);
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new
DataOutputStream([Link]());
String msg="";
while(![Link]("bye"))
{
msg=[Link]();
[Link](msg);
msg=[Link]();
[Link]("Server Says:"+msg);
} [Link]();
}
}
Server Program
import [Link].*;
import [Link].*;
class ServerChatApp
{
public static void main(String args[])throws IOException {
ServerSocket ss=new ServerSocket(9090);
Socket s=[Link]();
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new
DataOutputStream([Link]());
String msg="";
while(![Link]("bye"))
{
msg=[Link]();
[Link]("Client Says:"+msg);
msg=[Link]();
[Link](msg);
}
[Link]();
}
}
Datagram Sockets, Datagram Packets:
-In Java, datagram socketsand datagram packetsare used to
implement UDP (User Datagram Protocol)communication.
-UDP is a connectionless protocol that allows sending and receiving
datagrams (packets) over the network without establishing a
connection between the sender and receiver.
-A DatagramSocket is used to send and receive datagrams(UDP
packets). It is the Java class that provides methods for
communication over the network using UDP.
-You can create a DatagramSocket either with a specified port
number or without a port number
-To send data, you first need to create a DatagramPacket containing
the data and then send it using the send()method of DatagramSocket
. -To receive data, you create an empty DatagramPacketand use the
receive() method to get the incoming packet.
-DatagramPacketis a container for the data sent or received via
DatagramSocket
-It contains the data, the sender's IP address, and the port number.
DatagramPacket Class:
-Constructors: oDatagrampacket(byte data[],int size)
oDatagrampacket(byte data[],int offset,int size)
oDatagrampacket(byte data[],int size,InetAddress addr,int port)
oDatagrampacket(byte data[],int offset, int size,InetAddress addr,int
port);
-Methods:
oInetAddress getAddress()
oint getPort() obyte[] getData() oint getLength() oint getOffset()
ovoid setAddress(InetAddress addr) ovoid setData(byte data[]) ovoid
setLength(int length) ovoid setPort(int port)
DatagramSocket Class:
-Constructors: oDatagramSocket() oDatagramSocket(int port)
oDatagramSocket(int port,InetAddress addr)
oDatagramSocket(DatagramSocketImpl obj)
-Methods:
void send(Datagrampacket obj)
void receive(Datagrampacket obj) int getLocalport();
int getPort(); void connect(InetAddress addr,int port);
void disconnect();
void close();
Example:
Datagram Packet Sender
import [Link].*;
class DataSender
{
public static void main(String args[])throws Exception { DatagramSocket
ds=new DatagramSocket();
String str="Welcome to world of network programming";
byte data[]=[Link]();
int len=[Link]();
InetAddress addr=[Link]("[Link]"); DatagramPacket
dp=new DatagramPacket(data,len,addr,5555); [Link](dp);
[Link]();
}
}
Datagram Packet Receiver
import [Link].*;
class DataReceiver
{
public static void main(String args[])throws Exception { DatagramSocket
ds=new DatagramSocket(5555);
byte data[]=new byte[1024];
DatagramPacket dp=new DatagramPacket(data,1024);
[Link](dp);
String str=new String([Link](),
0,
[Link]());
[Link](str);
[Link]();

}
}

You might also like