0% found this document useful (0 votes)
5 views18 pages

AJP Unit 2 QB Bank

The document covers various aspects of network programming in Java, including server socket methods, Java networking packages, and socket types. It explains the advantages of Java sockets, their applications, and provides examples of socket programming, file handling, and common network protocols. Additionally, it discusses the URL class and constructors of the FileReader and FileWriter classes.

Uploaded by

srnarayanan_slm
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)
5 views18 pages

AJP Unit 2 QB Bank

The document covers various aspects of network programming in Java, including server socket methods, Java networking packages, and socket types. It explains the advantages of Java sockets, their applications, and provides examples of socket programming, file handling, and common network protocols. Additionally, it discusses the URL class and constructors of the FileReader and FileWriter classes.

Uploaded by

srnarayanan_slm
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/ 18

Unit II

NETWORK PROGRAMMING IN JAVA


Part I( 1 Mark)

1. Which methods are commonly used in Server Socket class?


a) Public Output Stream get Output Stream ()
b) Public Socket accept ()
c) Public synchronized void close ()
d) Public void connec

2. Which Java package is primarily used for networking?


a) java.net
b) java.util
c) java.io
d) java.swing

3 Which class is used to create a server socket?


a) Socket
b) ServerSocket
c) NetSocket
d) HostSocket

4. Which method is used to read data from an InputStream object?


a) readData()
b) pullData()
c) fetch()
d) read()

5. What does the InetAddress class represent?


a) URL
b) IP Address
c) Host Name
d) Domain Name

6. Which protocol ensures error-free data transmission?


a) HTTP
b) UDP
c) FTP
d) TCP
7. Which class provides methods to work with URLs?
a) URLConnection
b) HttpURL
c) NetURL
d) URL

8. Which exception is thrown when a connection cannot be established with a remote server?
a) IOException
b) ConnectionException
c) NetworkException
d) UnknownHostException

9. What is the default port number for HTTP?


a) 25
b) 8080
c) 21
d) 80

10. Which class provides methods to create a client-side socket in Java?


a) ServerSocket
b) NetSocket
c) Socket
d) ClientSocket

10. Which Java class represents a socket address, consisting of an IP and port number?
a) InetAddress
b) InetPort
c) SocketAddress
d) InetSocketAddress

11. Template which can send and receive JMS messages with much less code
a) JmsTemplate
b) EMail
c) All of the mentioned
d) None of the mentioned

12. The template handles the boilerplate tasks for you and also converts the JMS API
JMSException hierarchy into Spring runtime exception:-
a) org.springframework.jms.Jms
b) org.springframework.jms.JmsException
c) org.springframework.jms.JmsTemplate
d) none of the mentioned
13. To address different JMS APIs, Spring provides :-
a) JmsTemplate
b) JmsTemplate102
c) All of the mentioned
d) None of the mentioned

14. Before you can send and receive JMS messages, you need to install a JMS message broker:-
a) Apache ActiveM
b) Apache Active
c) Apache MQ
d) Apache ActiveMQ

15. The application layer protocol used by a Telnet application is ________


a) Telnet
b) FTP
c) HTTP
d) SMTP

16. _______ allows you to connect and login to a remote computer


a) Telnet
b) FTP
c) HTTP
d) SMTP

17. Telnet is used for _______


a) Television on net
b) Network of Telephones
c) Remote Login
d) Teleshopping site

18. Which operating mode of telnet is full duplex?


a) default mode
b) server mode
c) line mode
d) character mode

19. Which class creats a TCP server socket, bound to the specified port ?
a) Socket
b)InetAddress
c)ServerSocket
d)DatagramSocket
20. Which method of URL class returns the object of URL Connection class ?
a) getLocalHost()
b) openConnection()
c) getByName(String host)
d) getHostAddress()

Part II
1. Define Sockets programming in java networking with example.

A socket is one endpoint of a two-way communication link between two programs


running on the network. 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. A socket connection means the two
machines have information about each other’s network location (IP Address) and TCP port.
The java.net.Socket class represents a Socket. To open a socket

Socket socket = new Socket(“127.0.0.1”, 5000)


 The first argument – IP address of Server. ( 127.0.0.1 is the IP address of localhost, where
code will run on the single stand-alone machine).
 The second argument – TCP Port. (Just a number representing which application to run on
a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

Communication - To communicate over a socket connection, streams are used to both input
and output the data.
Closing the connection - The socket connection is closed explicitly once the message to the
server is sent.

Server Program
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);}
}
}
2. Write notes on Types of Socket in java.

1. Datagram Sockets: Datagram sockets allow processes to use the User Datagram Protocol
(UDP). It is a two-way flow of communication or messages. It can receive messages in a
different order from the sending way and also can receive duplicate messages. These sockets
are preserved with their boundaries. The socket type of datagram socket is SOCK_DGRAM.

2. Stream Sockets: Stream socket allows processes to use the Transfer Control Protocol
(TCP) for communication. A stream socket provides a sequenced, constant or reliable, and
two-way (bidirectional) flow of data. After the establishment of connection, data can be read
and written to these sockets in a byte stream. The socket type of stream socket is
SOCK_STREAM.

3. Raw Sockets: Raw Socket provide user access to the Internet Control Message Protocol
(ICMP). Raw sockets are not used for most applications. These sockets are the same as the
datagram oriented, their characteristics are dependent on the interfaces. They provided
support in developing new communication protocols or for access to more facilities of an
existing protocol. Only the super users can access the Raw Sockets. The socket type of Raw
Socket is SOCK_RAW.

4. Multicast Socket :The multicast datagram socket class is useful for sending and receiving IP
multicast packets. A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for
joining "groups" of other multicast hosts on the internet. A multicast group is specified by a
class D IP address and by a standard UDP port number.

3.Give the Advantages of Java Sockets

Platform Independence − One of the biggest advantages of Java Sockets is that they are
platform-independent. This means that the same Java code can be run on multiple operating
systems and devices without the need for modification. This allows for easy deployment of
network-based applications across different systems and ensures that the application can be
run on different devices without the need for platform-specific code.

Easy to Use − Java Sockets are also relatively easy to use, even for developers who are new to
network programming. The Java API provides a simple, consistent interface for creating and
managing sockets, which makes it easy to implement network-based applications without
needing to understand the underlying network protocols.

Scalability − Java Sockets are highly scalable, making them suitable for large-scale network-
based applications. They can easily handle thousands of simultaneous connections and can be
used to create distributed systems that can handle high levels of traffic.
Security − Java Sockets provide built-in support for secure communication, including SSL and
TLS encryption. This makes it easy to create secure network-based applications and ensures
that sensitive data is protected while in transit.

Multithreading − Java Sockets support multithreading, which means that multiple threads can
be used to handle multiple connections simultaneously. This improves the performance of
network-based applications and allows them to handle a large number of requests without
becoming overloaded.

4.Mention the application of Java Socket

Chat Applications − Java Sockets are often used to create chat applications, such as instant
messaging programs and online chat rooms. These types of applications typically use a client-
server architecture, where clients connect to a central server to send and receive messages.

File Transfer Applications − Java Sockets can also be used to create file transfer applications,
such as peer-to-peer file sharing programs. These types of applications use a peer-to-peer
architecture, where each device acts as both a client and a server. This allows for direct
communication between devices, which can improve the speed and reliability of file transfers.

Remote Control Applications − Java Sockets can also be used to create remote control
applications, such as remote desktop software. These types of applications use a client-server
architecture, where a client connects to a remote server to control the desktop of the server.
This allows users to access and control their desktop from any device with an internet
connection.
Multiplayer Games − Java Sockets are also commonly used to create multiplayer games, such
as online role-playing games and first-person shooters. These types of applications typically
use a client-server architecture, where clients connect to a central server to play the game.
The server acts as the intermediary between clients, handling communication and game logic.

IoT Applications − Java Sockets can also be used in IoT (Internet of Things) applications, such
as smart home systems. These types of applications use a client-server architecture, where
IoT devices connect to a central server to send and receive data. This allows for remote
monitoring and control of the devices, as well as data collection and analysis.

5. Write brief description on Java URL


1. The URL class in java is a getaway to access any resource available on the web or
internet. URL is a Uniform Resource Locator that points to the resource like file,
directory, or image on the World Wide Web(www).
A URL contains many information:

2. Protocol: In this case, http is the protocol.


3. Server name or IP Address: In this case, www.javatpoint.com is the server name.
4. Port Number: It is an optional attribute. If we write
http//ww.javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If port number is
not mentioned in the URL, it returns -1.
5. File Name or directory name: In this case, index.jsp is the file name.

6. Engrave on diverse in java Socket.

1. Datagram Sockets: Datagram sockets allow processes to use the User Datagram Protocol
(UDP). It is a two-way flow of communication or messages. It can receive messages in a
different order from the sending way and also can receive duplicate messages. These sockets
are preserved with their boundaries. The socket type of datagram socket is SOCK_DGRAM.

2. Stream Sockets: Stream socket allows processes to use the Transfer Control Protocol
(TCP) for communication. A stream socket provides a sequenced, constant or reliable, and
two-way (bidirectional) flow of data. After the establishment of connection, data can be read
and written to these sockets in a byte stream. The socket type of stream socket is
SOCK_STREAM.

3. Raw Sockets: Raw Socket provide user access to the Internet Control Message Protocol
(ICMP). Raw sockets are not used for most applications. These sockets are the same as the
datagram oriented, their characteristics are dependent on the interfaces. They provided
support in developing new communication protocols or for access to more facilities of an
existing protocol. Only the superusers can access the Raw Sockets. The socket type of Raw
Socket is SOCK_RAW.

4. Multicast Socket :The multicast datagram socket class is useful for sending and receiving IP
multicast packets. A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for
joining "groups" of other multicast hosts on the internet. A multicast group is specified by a
class D IP address and by a standard UDP port number.
7. Constructors of FileReader class in java

FileReader - Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class. It is character-oriented class which is used for file handling
in java.

Constructors of FileReader class

Constructor Description

FileReader(String It gets filename in string. It opens the given file in read mode. If file
file) doesn't exist, it throws FileNotFoundException.

FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file
doesn't exist, it throws FileNotFoundException.

import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}

}
8. Explain in short about FileInputStream in java.

Java FileInputStream class obtains input bytes from a file. It is used for reading byte-
oriented data (streams of raw bytes) such as image data, audio, video etc. You can also read
character-stream data. But, for reading streams of characters, it is recommended to
use FileReader class.

Scanner : The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read Strings:
import java.util.Scanner; // Import the Scanner class

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output user input
}
}

9. Write notes on Java FileWriter class.


Java FileWriter of java.io package is used to write data in character form to file. Java
FileWriter class is used to write character-oriented data to a file. It is a character-
oriented class that is used for file handling in java.
 This class inherits from OutputStreamWriter class which in turn inherits from the Writer
class.

Java FileWriter Class Declaration

public class FileWriter extends OutputStreamWriter

// Java program to create a text File using FileWriter

import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
class GFG {
public static void main(String[] args)
throws IOException
{
// initialize a string
String str = "ABC";
try {

// attach a file to FileWriter


FileWriter fw
= new FileWriter("D:/data/file.txt");

// read each character from string and write


// into FileWriter
for (int i = 0; i < str.length(); i++)
fw.write(str.charAt(i));

System.out.println("Successfully written");

// close the file


fw.close();
}
catch (Exception e) {
e.getStackTrace();
}
}
}

10. Discuss about java FileOutputStream:

FileOutputStream is an outputstream for writing data/streams of raw bytes to file or storing


data to file. FileOutputStream is a subclass of OutputStream. To write primitive values into a
file, we use FileOutputStream class.
Through the above image, we can understand that when we run the java program, the data is
stored in the RAM. Now, suppose the variable data stored in RAM, we want to access that
data and bring it to a file in our hard disk. So, we will create an object of OutputStream in the
RAM and that will point to a file referencing to hard disk.

Declaration:
public class FileOutputStream extends OutputStream

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}

OUTPUT
Success...

11. List the Common Network Protocols and it classes in java and explain.

 Transmission Control Protocol (TCP) – TCP or Transmission Control Protocol


allows secure communication between different applications. TCP is a
connection-oriented protocol which means that once a connection is
established, data can be transmitted in two directions.

 User Datagram Protocol (UDP) – UDP or User Datagram Protocol is a


connection-less protocol that allows data packets to be transmitted between
different applications. UDP is a simpler Internet protocol in which error-
checking and recovery services are not required.

Java Networking classes

The classes covered in the java.net package are given as follows –


CacheRequest – The CacheRequest class is used in java whenever there is a need to
store resources in ResponseCache.

CookieHandler – The CookieHandler class is used in Java to implement a callback


mechanism for securing up an HTTP state management policy implementation inside
the HTTP protocol handler.
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. An IP address is expressed by a 32-bit or 128-bit unsigned number.
InetAddress can handle both IPv4 and IPv6 addresses.
Socket – The Socket class is used to create socket objects that help the users in
implementing all fundamental socket operations.
Proxy – A proxy is a changeless object and a kind of tool or method or program or
system, which serves to preserve the data of its users and computers.
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.

12. Write notes Uniform Resource Loader and its classes in java

The java.net.URL class provides many methods. The important methods of URL class are given
below.

Method Description

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.

Example of Java URL class

//URLDemo.java
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);}
}
}

Output:

Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

Part III
1. Discuss the key components of Java Messaging Services (JMS) and how they facilitate reliable and
asynchronous communication in distributed systems.

Java Message Service (JMS) is a Java-based messaging API that allows applications to communicate in a
loosely coupled, reliable, and asynchronous manner. JMS provides a standardized way for Java
applications to send and receive messages, making it easier to develop distributed systems. The key
components of JMS include:

Message: The fundamental unit of communication in JMS. A message can contain data, such as text or
binary content, and additional header information. There are two main types of messages in JMS:
TextMessage: Contains a java.lang.String object.
BytesMessage: Contains a stream of uninterpreted bytes.
ObjectMessage: Contains a serializable Java object.
MapMessage: Contains name-value pairs.
StreamMessage: Contains a stream of primitive values.

Producer: A JMS producer is responsible for creating and sending messages to a JMS destination, such as
a queue or a topic. The MessageProducer interface provides methods to send messages to the
destination.

Consumer: A JMS consumer is responsible for receiving and processing messages from a JMS
destination. Consumers subscribe to a specific destination (queue or topic) and use the
MessageConsumer interface to retrieve messages.

Queue: A point-to-point messaging model where each message is consumed by a single consumer. In
JMS, queues are used for point-to-point communication. Multiple consumers can listen to the same
queue, but each message is consumed by only one consumer.

Topic: A publish-subscribe messaging model where each message can be consumed by multiple
subscribers. In JMS, topics are used for publish-subscribe communication. Multiple subscribers can
subscribe to the same topic, and each subscriber receives a copy of the message.

ConnectionFactory: An object that is used to create connections to the JMS provider. It is typically
configured with connection parameters, such as the JMS provider's URL.
Connection: Represents a connection to the JMS provider. The Connection interface provides methods
to create sessions.

Session: A session is a single-threaded context for producing and consuming messages. It is created by a
connection and provides a transactional context if needed. Sessions are used to create producers and
consumers.

MessageListener: An interface implemented by the application to asynchronously receive messages. A


consumer can register a MessageListener to handle incoming messages.

By using these components, JMS facilitates reliable and asynchronous communication in distributed
systems. Producers can send messages to destinations, and consumers can asynchronously receive and
process these messages.

2. Write detail notes on Reading and Writing Data between server and Client

This client program is straightforward and simple because the echo server implements a simple
protocol. The client sends text to the server, and the server echoes it back. When your client
programs are talking to a more complicated server such as an HTTP server, your client program
will also be more complicated. However, the basics are much the same as they are in this
program:

1. Open a socket.
2. Open an input stream and output stream to the socket.
3. Read from and write to the stream according to the server's protocol.
4. Close the streams.
5. Close the socket.

Java API that can be used to read and write files in Java:
FileReader, FileInputStream, Scanner, FileWriter,
FileOutputStream, etc.

FileReader - Java FileReader class is used to read data from the file. It returns data in byte
format like FileInputStream class. It is character-oriented class which is used for file handling
in java.

Constructors of FileReader class

Constructor Description

FileReader(String It gets filename in string. It opens the given file in read mode. If file
file) doesn't exist, it throws FileNotFoundException.

FileReader(File file) It gets filename in file instance. It opens the given file in read mode. If file
doesn't exist, it throws FileNotFoundException.

import java.io.FileReader;
public class FileReaderExample {
public static void main(String args[])throws Exception{
FileReader fr=new FileReader("D:\\testout.txt");
int i;
while((i=fr.read())!=-1)
System.out.print((char)i);
fr.close();
}
}

FileInputStream - Java FileInputStream class obtains input bytes from a file. It is used for
reading byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You can
also read character-stream data. But, for reading streams of characters, it is recommended to
use FileReader class.

Scanner : The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read Strings:

import java.util.Scanner; // Import the Scanner class

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input


System.out.println("Username is: " + userName); // Output user input
}
}

Java FileWriter class of java.io package is used to write data in character form to file. Java
FileWriter class is used to write character-oriented data to a file. It is a character-oriented
class that is used for file handling in java.
 This class inherits from OutputStreamWriter class which in turn inherits from the Writer
class.

3. Elaborate Telnet Application in java in detail

o The main task of the internet is to provide services to users. For example, users want to
run different application programs at the remote site and transfers a result to the local
site. This requires a client-server program such as FTP, SMTP. But this would not allow
us to create a specific program for each demand.
Types of Telnet: At Local Site

o Keystrokes are accepted by the terminal driver when the user types at the terminal.
o Terminal Driver passes these characters to OS.
o Now, OS validates the combination of characters and opens the required application.

At the remote site

The commands in NVT forms are transmitted to the TCP/IP at the remote machine.
Here, the characters are delivered to the operating system and then pass to the TELNET
server. The TELNET server transforms the characters which can be understandable by a
remote computer.

The Procedure of Remote Login


o When the user types something on the local computer, the local operating system
accepts the character.
o The local computer does not interpret the characters, it will send them to the TELNET
client.
o TELNET client transforms these characters to a universal character set called Network
Virtual Terminal (NVT) characters and it will pass them to the local TCP/IP protocol
Stack.
o Commands or text which are in the form of NVT, travel through the Internet and it will
arrive at the TCP/IP stack at the remote computer.
o Characters are then delivered to the operating system and later on passed to the
TELNET server.
o Then TELNET server changes those characters to characters that can be understandable
by a remote computer.
o The remote operating system receives characters from a pseudo-terminal driver, which
is a piece of software that pretends that characters are coming from a terminal.
o The operating system then passes the character to the appropriate application program.

4. Can you provide a comprehensive explanation of the Telnet application implemented in Java,
including detailed information on its functionalities and components?

5. Provide detailed information on the process of reading and writing data between a server and client,
with a focus on the mechanisms and methods involved in Java programming?

6. Can you elaborate on the essential elements of Java Messaging Services (JMS) and their roles in
enabling dependable and asynchronous communication within distributed systems?

You might also like