[go: up one dir, main page]

0% found this document useful (0 votes)
7 views17 pages

UNIT-V Basics of Network Programming

This document provides an overview of network programming in Java, covering key concepts such as sockets, client-server architecture, and internet addressing. It explains the use of TCP/IP and UDP protocols, along with the InetAddress, URL, and URLConnection classes for network communication. Additionally, it includes examples of client-server applications and chat applications using Java's networking capabilities.

Uploaded by

nehaukarde83
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)
7 views17 pages

UNIT-V Basics of Network Programming

This document provides an overview of network programming in Java, covering key concepts such as sockets, client-server architecture, and internet addressing. It explains the use of TCP/IP and UDP protocols, along with the InetAddress, URL, and URLConnection classes for network communication. Additionally, it includes examples of client-server applications and chat applications using Java's networking capabilities.

Uploaded by

nehaukarde83
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
You are on page 1/ 17

UNIT-V Basics of Network Programming

UNIT-V Basics of Network Programming

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 1
UNIT-V Basics of Network Programming

Syllabus

- Socket Overview: Client/Server, reserved Sockets, proxy servers, Internet Addressing


- Java and the Net: The networking classes and interfaces, InetAddress: Factory Methods,
Instance Methods
- TCP/IP Client and Server Sockets, datagram sockets, datagram packets
- The URL Class, URLConnection class

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 2
UNIT-V Basics of Network Programming

Java NetWorking

- 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 java.net 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.

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 3
UNIT-V Basics of Network Programming

- Server Work
 The server listens for incoming connections using a ServerSocket.
 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 1023 are reserved ports.
- For example, HTTP (HyperText 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:

1. IP 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

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 4
UNIT-V Basics of Network Programming

 Class C: 192 to 223


 Class D: 224 to 239
 Class E: 240 to 255

2. Domain Name System (DNS):


- The Domain Name System (DNS) translates human-readable domain names (e.g.,
www.google.com) into machine-readable IP addresses (e.g., 142.250.190.14).
- 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.

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 5
UNIT-V Basics of Network Programming

InetAddress:

- In Java, InetAddress is a class in the java.net 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()

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 6
UNIT-V Basics of Network Programming

Example:

import java.net.*;
class InetAddressDemo
{
public static void main(String args[])throws UnknownHostException
{
InetAddress addr=InetAddress.getLocalHost();
System.out.println(addr);
addr=InetAddress.getByName("www.msbte.ac.in");
System.out.println(addr);
System.out.println("Is Multicast Addresss:"+addr.isMulticastAddress());
InetAddress addr1[]=InetAddress.getAllByName("www.google.com");
for(int i=0;i<addr1.length;i++)
{
System.out.println(addr1[i]);
}
}
}

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 7
UNIT-V Basics of Network Programming

URL Class:

- In Java, the URL class is part of the java.net 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: -
http://www.vjtechacademy.com/about.html
- 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();

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 8
UNIT-V Basics of Network Programming

- Example:

import java.net.*;
class URLDemo
{
public static void main(String args[])throws MalformedURLException
{
URL u1=new URL("https://www.vjtechacademy.in:80/about.html");
System.out.println("Protocol Name:"+u1.getProtocol());
System.out.println("Host Name:"+u1.getHost());
System.out.println("Port No:"+u1.getPort());
System.out.println("File Path:"+u1.getFile());
}
}
OUTPUT:

Protocol Name:https
Host Name:www.vjtechacademy.in
Port No:80
File Path:/about.html

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 9
UNIT-V Basics of Network Programming

URLConnection Class:

- It is used to access attributes of remote resources.


- The URLConnection class in Java is part of the java.net 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 java.net.*;
import java.util.*;
import java.io.*;
class URLConnectionDemo
{
public static void main(String args[])throws MalformedURLException,IOException
{
URL u1=new URL("https://www.facebook.com/");
URLConnection u2=u1.openConnection();
System.out.println("Content Type:"+u2.getContentType());
System.out.println("Content Length:"+u2.getContentLength());
System.out.println("Today Date:"+new Date(u2.getDate()));
System.out.println("Expiration Date:"+new Date(u2.getExpiration()));
System.out.println("Last Modified Date:"+new Date(u2.getLastModified()));

}
}

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 10
UNIT-V Basics of Network Programming

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 java.net package
provides classes for networking, including Socket for the client-side and ServerSocket for
the server-side.
- ServerSocket and Socket both are predefined classes which are present under java.net 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:
o Socket(String HostName,int port)
o Socket(InetAddress addr,int port)
- Methods:
o InetAddress getInetAddress();
o int getPort();
o int getLocalPort();
o InputStream getInputStream()
o OutputStream getOutputStream()
o void close()

ServerSocket Class:

- Constructors:
o ServerSocket(int port)
o ServerSocket(int port , int maxqueue)

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 11
UNIT-V Basics of Network Programming

o ServerSocket(int port,int maxqueue,InetAddress addr);


- Methods:
o accept();

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 12
UNIT-V Basics of Network Programming

Example:

//Client Program
import java.net.*;
import java.io.*;
class Client
{
public static void main(String args[])throws Exception
{
Socket s=new Socket("localhost",9090);
InputStream in=s.getInputStream();
OutputStream out=s.getOutputStream();
byte str[]="Hi Server".getBytes();
out.write(str);
s.close();
}
}

//Server Program
import java.net.*;
import java.io.*;
class Server
{
public static void main(String args[])throws Exception
{
ServerSocket ss=new ServerSocket(9090);
Socket s1=ss.accept();
InputStream in=s1.getInputStream();
OutputStream out=s1.getOutputStream();
int c;
while((c=in.read())!=-1)
{
System.out.print((char)c);
}
s1.close();
}
}

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 13
UNIT-V Basics of Network Programming

Program: Chat Application using TCP/IP Client and Server Sockets.

Client Program

import java.net.*;
import java.io.*;
class ClientChatApp
{
public static void main(String args[])throws IOException
{
Socket s=new Socket("localhost",9090);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
String msg="";
while(!msg.equals("bye"))
{
msg=br.readLine();
dout.writeUTF(msg);
msg=din.readUTF();
System.out.println("Server Says:"+msg);
}
s.close();
}
}

Server Program

import java.net.*;
import java.io.*;
class ServerChatApp
{
public static void main(String args[])throws IOException
{
ServerSocket ss=new ServerSocket(9090);
Socket s=ss.accept();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
String msg="";
while(!msg.equals("bye"))
{
msg=din.readUTF();
System.out.println("Client Says:"+msg);
msg=br.readLine();
dout.writeUTF(msg);
}
s.close();
}
}

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 14
UNIT-V Basics of Network Programming

Datagram Sockets, Datagram Packets:

- In Java, datagram sockets and datagram packets are 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 DatagramPacket and use the receive() method to get
the incoming packet.
- DatagramPacket is 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:
o Datagrampacket(byte data[],int size)
o Datagrampacket(byte data[],int offset,int size)
o Datagrampacket(byte data[],int size,InetAddress addr,int port)
o Datagrampacket(byte data[],int offset, int size,InetAddress addr,int port);

- Methods:
o InetAddress getAddress()
o int getPort()
o byte[] getData()
o int getLength()
o int getOffset()
o void setAddress(InetAddress addr)
o void setData(byte data[])
o void setLength(int length)
o void setPort(int port)

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 15
UNIT-V Basics of Network Programming

DatagramSocket Class:

- Constructors:
o DatagramSocket()
o DatagramSocket(int port)
o DatagramSocket(int port,InetAddress addr)
o DatagramSocket(DatagramSocketImpl obj)
- Methods:
o void send(Datagrampacket obj)
o void receive(Datagrampacket obj)
o int getLocalport();
o int getPort();
o void connect(InetAddress addr,int port);
o void disconnect();
o void close();

Example:

Datagram Packet Sender

import java.net.*;
class DataSender
{
public static void main(String args[])throws Exception
{
DatagramSocket ds=new DatagramSocket();

String str="Welcome to world of network programming";


byte data[]=str.getBytes();
int len=str.length();
InetAddress addr=InetAddress.getByName("127.0.0.1");
DatagramPacket dp=new DatagramPacket(data,len,addr,5555);

ds.send(dp);

ds.close();
}
}

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 16
UNIT-V Basics of Network Programming

Datagram Packet Receiver

import java.net.*;
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);

ds.receive(dp);

String str=new String(dp.getData(),0,dp.getLength());

System.out.println(str);

ds.close();

}
}

Java Language by Prof. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 17

You might also like