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

JPR Unit 5 Q & A

The document provides an overview of network programming basics, focusing on concepts such as networking, protocols, client-server models, sockets, and the differences between TCP/IP and UDP. It explains the advantages and disadvantages of networking, the use of various Java classes like Socket and ServerSocket, and details on how client-server communication works. Additionally, it covers the role of ports, the InetAddress class, and the definition of datagrams in UDP communication.

Uploaded by

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

JPR Unit 5 Q & A

The document provides an overview of network programming basics, focusing on concepts such as networking, protocols, client-server models, sockets, and the differences between TCP/IP and UDP. It explains the advantages and disadvantages of networking, the use of various Java classes like Socket and ServerSocket, and details on how client-server communication works. Additionally, it covers the role of ports, the InetAddress class, and the definition of datagrams in UDP communication.

Uploaded by

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

JPR Unit – 5: Basics of Network Programming

Questions and Answers:

1. What is networking?

Ans.

 Networking:
 Networking is the process of connecting two or more computers to share data and resources like
files, printers, or internet access.
 In Java, networking means communication between programs running on different machines
using TCP/IP or UDP protocols.
 Java provides the java.net package, which includes classes like :-
o Socket and ServerSocket (for TCP).
o DatagramSocket (for UDP).
o URL and URLConnection (for web communication).
 Example Use :-
 Sending data from a client program to a server program.

2. What are the advantages and disadvantages of networking?

Ans.

 Advantages:

1. Resource Sharing: Devices like printers, files, and internet can be shared.
2. Communication: Enables email, messaging, and video calls.
3. Centralized Data Access: Data can be stored and accessed from one location.
4. Remote Access: Users can access the network from different locations.

 Disadvantages:

1. Security Risks: Networks are vulnerable to hacking and viruses.


2. Data Loss: Centralized systems may lose data if backups are not maintained.
3. Setup Cost: Installing and maintaining networks can be expensive.
4. Dependency: If the network fails, connected systems may not work.

3. What is protocol? List out at least two protocols.

Ans.

 Protocol:
 Protocol is a set of rules and standards that define how data is transmitted and received over a
network.
 It ensures proper communication between devices or programs by specifying how connections
are made, how data is formatted, and how errors are handled.
 List of Protocols:

1. TCP (Transmission Control Protocol) – Reliable, connection-oriented protocol.


2. UDP (User Datagram Protocol) – Fast, connectionless protocol with no delivery guarantee.

4. Explain with suitable diagram the HTTP communication between web server and web client.

Ans.

 HTTP communication between web server and web client:

 HTTP (Hyper Text Transfer Protocol) is a communication protocol used for data exchange
between a web client (browser) and a web server.
 When a user enters a URL, the client sends an HTTP request to the server.
 The server processes the request and sends back an HTTP response (like an HTML page, image,
etc.).

 Steps in HTTP Communication Process -

1. Client creates a TCP connection to the server.


2. Client sends an HTTP Request (e.g., GET or POST)
3. Server processes the request and sends an HTTP Response.
4. Response is displayed in the browser.

 Diagram –

 Example –

o URL Entered: http://www.google.com


o Client sends: GET / HTTP/1.1
o Server responds: With the HTML code of Google’s homepage.
o Client displays: The homepage in the browser window.

5. What is client-server model?

Ans.

 Client Server Model:

 The Client/Server model is a type of network architecture where two types of devices interact -
clients and servers.
 In this model -
o The client sends a service request to the server.
o The server processes the request and sends back a response.
o They communicate using well-established protocols such as HTTP, FTP, or TCP/IP.
 Client and Server Roles -
o A client is any device or software that wants to use the resources of a server.
o A server is a device or program that offers resources or services like data, files, or printer
access.
 Examples of Servers -
o Web Server: Shares web pages.
o Print Server: Manages network printers.
o Disk Server: Provides shared disk space.
 Working -
o A single server can handle multiple clients at once.
o Each client session is unique, even if connected to the same port.
o To handle many clients at the same time, the server must be multithreaded or support
I/O multiplexing.
 Example -
o A browser (client) sends a request to www.google.com.
o Google’s web server processes it and returns the web page.
 Diagram -
6.What is socket? Define it. How it works?

Ans.

🔷 Socket:

 A socket is one endpoint of a two-way communication link between two programs running on a
network.
 In Java networking, a socket acts as an interface between an application and the network,
allowing the application to send and receive data over the internet using TCP or UDP protocols.

🔷 Socket Overview -

 Sockets are bound to a specific IP address and port number.


 They are used for bi-directional (two-way) communication between the client and server.
 Java provides built-in classes in the java.net package to implement socket communication.

🧩 Concept -

 A client socket connects to a server.


 The server socket listens for incoming connections and accepts them.
 Once the connection is established, both sides use input and output streams to communicate.

🔹 Client Socket -

 Represented by: Socket class.


 Used to initiate connection to the server.
 Requires server’s IP and port number.

🔹 Server Socket -

 Represented by: ServerSocket class


 Listens for incoming requests
 Accepts client connection using .accept()

🔁 Working of Socket Communication:

1. Server creates a ServerSocket on a specific port and waits.


2. Client creates a Socket and connects to server’s IP and port.
3. Server accepts the connection and returns a Socket object.
4. Both can now communicate using input/output streams.

📘 Java Classes Used -

 Socket – for client-side communication.


 ServerSocket – for server-side listening.
 InputStream and OutputStream – for reading and writing data.

🔹 Diagram –

7.Describe client/server networking in detail.

Ans.

Client/Server Networking:

 Client/Server Networking is a communication model where clients and servers interact over a
network using well-established protocols.
 The client sends a request for a service, and the server processes and responds to that request.

🔷 Working -

 The client makes a service request to the server (e.g., access a webpage).
 The server listens to the request and responds with the required resource or action.
 Communication takes place using standard protocols such as HTTP, FTP, SMTP, etc.
 Each client-server session is unique, even if many clients connect to the same server port.

🔷 Key Concepts -

 A server is a system or program that shares its resources like processing power, storage, web
content, or printers.
 Types of servers include:
o Web Server (stores web pages)
o Disk Server (shares disk space)
o Print Server (manages networked printers)
 A client is any system or application that requests access to these shared resources.
 A server can handle multiple client connections at once using multithreading or I/O
multiplexing.

🔷 Diagram –

8.What is port?

Ans.

🔹 Port:

 A port is a logical communication endpoint used by computers to identify specific services or


applications running on a device.
 It ensures that data sent over the network reaches the correct process or program.

🔹 Need of ports -

 If a computer handled only one task over the network, an IP address alone would be enough.
 But modern computers perform multiple tasks simultaneously—such as handling email, FTP,
and web browsing—so ports help manage this by assigning a unique number to each service.

🔹 Port Characteristics -
 A port number is a 16-bit number ranging from 1 to 65535.
 Ports are not physical, like USB or Ethernet ports—they are logical identifiers.
 Each port can be associated with a specific service (e.g., HTTP, FTP, etc.).

🔹 Examples of Well-Known Port Numbers:

Service Port Number


FTP 21
Telnet 23
HTTP (Web) 80
Echo 7
Who Is 43
Finger 79

 Note –
o Ports 1–1023 are reserved for standard services.
o These are called well-known ports.

🔹 Port Use in Java -

Socket socket = new Socket("localhost", 8080);

 In this code, 8080 is the port number used to connect to a specific service on the server.

🔹 Analogy -

 If your computer is a hotel (IP address), then each port number is like a room number.
 Multiple services (guests) can stay in the same hotel, but they must each have a different room
(port) to function properly.

9.Explain use of Socket class.

Ans.

Uses of Socket class:

✅ 1. Establishing TCP Connections -

 The Socket class is used to create a TCP connection between a client and a server.

 It requires the server’s IP address and port number to connect.

✅ 2. Sending Data to Server -

 With the help of getOutputStream(), the socket allows sending data to the server.
 This stream sends bytes or characters to the connected destination.

✅ 3. Receiving Data from Server -

 The getInputStream() method helps in reading data sent by the server.

 It allows the client to receive server responses in real time.

✅ 4. Bi-Directional Communication -

 The Socket class supports two-way communication between client and server.

 Both input and output streams are used for interactive data exchange.

✅ 5. Real-Time Applications -

 It is used in chat apps, online games, and real-time messaging systems.

 These applications need continuous client-server interaction through sockets.

✅ 6. Graceful Connection Handling -

 Using the close() method, the socket can safely terminate the connection.

 This prevents data loss and releases system resources after communication ends.

10.Explain TCP/IP client sockets with suitable example.

Ans.

TCP/IP Client Sockets:

 In Java, TCP/IP client sockets are used when a client wants to establish a reliable connection to
a server using the TCP protocol.
 A client socket is created using the Socket class.
 It connects to a specific IP address (host) and port number of the server.
 Once connected, the client can –
o Send data using getOutputStream().
o Receive data using getInputStream().

🔹 Key Points -

 TCP provides connection-oriented, reliable, and ordered data transmission.


 The client initiates the connection; the server listens on a port.
 After communication, the socket should be closed to release resources.
🔹 Example – TCP/IP Client Socket in Java

import java.io.*;

import java.net.*;

public class SimpleClient

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

Socket socket = new Socket("localhost", 5000);

// Send message to server

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

out.println("Hello Server");

// Close the connection

socket.close();

🟢 Explanation in Simple Words -

 Client connects to server using Socket("localhost", 5000).


 It sends a text message "Hello Server" using PrintWriter.
 Then it closes the connection after sending the message.

11. Explain TCP/IP server sockets with suitable example.

Ans.

TCP/IP Server Sockets:

• In Java, TCP/IP server sockets are used when a server needs to listen for and accept incoming client
connections using the TCP protocol.
• A server socket is created using the ServerSocket class.
• The server listens on a specific port for client connections and accepts them when they arrive.
• Once a client connects, the server can –
o Receive data using getInputStream().
o Send data using getOutputStream().

🔹 Key Points -
• TCP is a connection-oriented protocol, ensuring reliable and ordered data transmission between client
and server.
• The server listens for incoming connections, while the client initiates the connection.
• After communication, the server should close the socket to release resources.

🔹 Example – TCP/IP Server Socket in Java

import java.io.*;

import java.net.*;

public class SimpleServer

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

// Create a server socket on port 5000

ServerSocket serverSocket = new ServerSocket(5000);

System.out.println("Server is running...");

// Accept client connection

Socket socket = serverSocket.accept();

// Read message from client

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));

String message = in.readLine();

System.out.println("Client says: " + message);


// Close sockets

socket.close();

serverSocket.close();

🟢 Explanation in Simple Words -

 The server creates a ServerSocket to listen for incoming connections on port 5000.
 When a client connects, the server accepts the connection and establishes a Socket for
communication.

12. What is the difference between TCP/IP and UDP?

Ans.

TCP/IP UDP
Connection-oriented protocol Connectionless protocol
Ensures reliable data transmission No guarantee of delivery
Slower due to error checking and flow control Faster, lightweight communication
Data is received in the same order sent Data may arrive out of order
Used for applications like web, email, file Used for video streaming, gaming, VoIP
transfer
Establishes connection before data transfer No connection setup required
More overhead due to reliability features Less overhead, suitable for real-time use
Example: HTTP, FTP, SMTP (TCP protocols) Example: DNS, DHCP, TFTP (UDP
protocols)

13. Explain the use of ServerSocket class.

Ans.

Uses of ServerSocket class:

1. Listening for Client Connections -

 The ServerSocket listens for incoming client requests on a specific port.


 Once a client attempts to connect, the server accepts the connection.
2. Establishing a Communication Channel -

 After accepting a client connection, a Socket object is created, allowing the server to send and
receive data to/from the client.

3. Handling Multiple Clients -

 The server can handle multiple clients by accepting each client connection one at a time.
 You can create separate threads to manage each client connection concurrently.

4. Creating a Reliable Server -

 It allows the server to handle multiple connections in a reliable manner.


 The server ensures that each client connection is properly established and maintained.

5. Server-Client Communication -

 ServerSocket allows two-way communication, enabling the server to send responses to the
client, making it suitable for applications like chat servers and file transfer.

6. Binding to a Specific Port -

 The ServerSocket binds to a particular port, ensuring that it listens for connections only on
that port, which is important for managing network traffic effectively.

14. Explain the use of InetAddress class.

Ans.

Uses of InetAddress class:

1. Getting Local Host Information -

 The InetAddress.getLocalHost() method retrieves the IP address of the local machine.


 It’s useful for identifying the local machine in networked applications.

2. Resolving Hostnames to IP Addresses -

 Using InetAddress.getByName("hostname"), you can convert a human-readable


hostname (like "google.com") into its corresponding IP address.

3. Checking if Host is Reachable -

 The isReachable() method checks if the host is reachable over the network, which is useful
for testing network connectivity before attempting communication.
4. Getting Hostname from IP Address -

 With InetAddress.getByAddress(byte[] address), you can convert an IP address


back into its corresponding hostname, helpful in reverse DNS lookups.

5. Working with IPv4 and IPv6 Addresses -

 InetAddress can handle both IPv4 and IPv6 addresses, making it adaptable to modern
networking protocols.
 You can distinguish between them using getHostAddress().

6. Getting Host Information -

 The getHostName() method retrieves the hostname of the machine associated with the IP
address, providing readable details about the connected host.

19. What is datagram?

Ans.

Datagram:

 A Datagram is a self-contained, independent packet of data used in UDP (User Datagram


Protocol) communication.
 Unlike TCP, which is connection-oriented and ensures reliable data transfer, UDP is
connectionless.
 This means that no formal connection is established between the sender and receiver before
data transmission.
 Consequently, UDP is faster but offers no guarantee that the datagram will reach its destination,
nor does it ensure the order of delivery.
 In Java, datagrams are handled using two key classes -

1. DatagramSocket :-

o This class is used to send and receive DatagramPacket objects.


o A DatagramSocket can listen on a specific port for incoming packets or send packets to
a specified address and port.

2. DatagramPacket :-

o Represents the data packet that is sent or received.


o A DatagramPacket contains the data, the destination IP address, and the port number.

Key Features of Datagram (UDP) Communication -


 Connectionless: No need to establish a connection before sending data.
 Faster but Unreliable: UDP is faster than TCP as there is no overhead for maintaining a
connection, but it does not guarantee packet delivery, order, or integrity.
 Ideal for: Real-time applications like video streaming, VoIP, online gaming, and DNS queries
where speed is prioritized over reliability.

20. Explain datagram packets in detail.

Ans.

Datagram Packets:

A DatagramPacket in Java is used to implement connectionless communication via UDP (User Datagram
Protocol). Unlike TCP, UDP does not establish a connection before data transmission, meaning that
delivery and order of the packets are not guaranteed. Each DatagramPacket carries both the data and
the necessary destination information (IP address and port number).

Key Points -

1. Self-contained Message: A DatagramPacket is an independent, self-contained message that is


sent from one machine to another. It includes data, destination address, and port number.
2. Unreliable Delivery: Since UDP is connectionless, the arrival of packets, their order, and the
data's integrity are not guaranteed. This makes DatagramPacket suitable for applications where
speed is important and occasional data loss is acceptable (like live streaming, gaming, or DNS
queries).

Constructors of DatagramPacket -

 DatagramPacket(byte[] buf, int len): Receives a packet of length len into a byte array buf.
 DatagramPacket(byte[] buf, int off, int len): Receives data starting at off for len bytes into
buf.
 DatagramPacket(byte[] buf, int len, InetAddress addr, int port): Sends data of length len to
the specified address and port.
 DatagramPacket(byte[] buf, int off, int len, InetAddress addr, int port): Sends data with an
offset to the specified address and port.

Methods of DatagramPacket -

1. getData(): Returns the byte array containing the data in the packet.
2. getAddress(): Returns the destination IP address.
3. getPort(): Returns the destination port number.
4. getLength(): Returns the length of valid data in the packet.

Advantages -

 Faster Communication: Datagram packets are faster than TCP because they do not require
establishing or maintaining a connection.
 Ideal for Real-Time Applications: It is well-suited for scenarios where low latency is critical, and
data loss is tolerable, like live streaming and gaming.

Disadvantages -

 Unreliable Delivery: Since UDP does not guarantee packet delivery, the data might be lost,
corrupted, or delivered out of order.
 No Flow Control: UDP does not provide any mechanism to control the flow of data between
sender and receiver, potentially causing congestion and packet loss if the network is overloaded.

21. Describe datagram server and client with example.

Ans.

Datagram Server:

 A Datagram Server receives data from clients using the UDP protocol, without creating a
connection.
 It uses DatagramSocket to listen for incoming packets.
 Example –

import java.net.*;

public class DatagramServer

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

DatagramSocket server = new DatagramSocket(9876);

byte[] buffer = new byte[1024];

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);


server.receive(packet);

System.out.println("Client: " + new String(packet.getData(), 0, packet.getLength()));

server.close();

 Explanation –

o The server opens port 9876 using DatagramSocket to wait for incoming UDP
packets.
o When a packet arrives, it prints the client message and then closes the socket.

Datagram Client:

 A Datagram Client sends a message to a server using UDP.


 It creates a DatagramPacket with the message and destination IP and port.
 Example –

import java.net.*;

public class DatagramClient

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

DatagramSocket client = new DatagramSocket();

String msg = "Hello Server";

InetAddress ip = InetAddress.getByName("localhost");

DatagramPacket packet = new DatagramPacket(msg.getBytes(), msg.length(), ip, 9876);

client.send(packet);
client.close();

 Explanation –

o The client creates a datagram packet with the message "Hello Server" and
sends it to port 9876 on the server.
o It does not wait for a response and immediately closes the socket.

You might also like