Network Programming with Java Exam

hizuhasu's version from 2016-06-02 13:12

Networking with Sockets in Java

Question Answer
What is the difference between the Socket class and the ServerSocket class? Objects of which classes are used to communicate using TCP sockets in a distributed Java application?• – is used by servers to listen for connection requests from clients;
– Should be bound to a known port to listen on,
– Accept method blocks until a client requests a connection.
– Returns a Socket object that represents the accepted connection.
• – End point for interprocess communication over the network.
– The client and server uses a Socket object to communicate with each other.
Shortly explain steps, which are executed by a sender, and steps, which are executed by a receiver, in order to communicate with each other using UDP sockets. Indicate also objects of which classes are used at each step.The class – represents a UDP socket for sending datagrams
step I. DatagramSocket object is created
ds = new DatagramSocket();
step II. Fill buf with data to sent
byte buf[] = new byte[256];
step III. Create a datagram
dp = new DatagramPacket(buf, buf.length, InetAddress.getByName(““),4711);
step IV. Send the datagram via the UDP socket

the class – represents a UDP socket for receiving datagrams

step I. Create byte[] b for recieveing datagrampacket
byte b[] = new byte[256];
step II. DatagramSocket object is created
dp = new DatagramPacket(b, b.length);
step III. Set timeout – the amount of time (in milliseconds) that receive() waits for datagram before throwing an
step IV. Receive a datagram
step V. Get data
byte[] data = dp.getData();
step VI. get source of packet
InetAddress source = dp.getAddress();
step VII. get source port of packet
int port = dp.getPort();
Shortly explain steps, which are executed by a sender, and steps, which are executed by a receiver, in order to communicate with each other using TCP sockets

Server Side

1. Open a server socket
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(4444);

2. The server's main loop, listen for incoming connections and handle request
while(listening) {
clientSocket = serverSocket.accept();
(new SimpleConHandler(clientSocket)).handle();

Get input/output streams from client socket
in = new BufferedInputStream(clientSocket.getInputStream());
out = new BufferedOutputStream(clientSocket.getOutputStream());

inMsg =;
3 Close connection to client

Client side

1. Open a socket Connection
Socket clientSocket = new Socket(Dstaddress,port);

Get input/output streams from client socket
in = new BufferedInputStream(clientSocket.getInputStream());
out = new BufferedOutputStream(clientSocket.getOutputStream());

inMsg =;
3 Close connection to client

Remote Method Invocation (RMI)

Question Answer
What is RMI ?

RMI allows applications to call object methods located remotely, sharing resources and processing load across systems. Unlike other systems for remote execution which require that only simple data types or defined structures be passed to and from methods, RMI allows any Java object type to be used - even if the client or server has never encountered it before.
What is UnicastRemoteObject and what is its use in Java RMI ?

The UnicastRemoteObject class provides support for point-to-point active object references (invocations, parameters, and results) using TCP streams. Extending UnicastRemoteObject makes your class capable of handling incoming calls, and is acceptable in many cases.
Describe steps needed to enable a distributed application in Java to use Java RMI for communication.

Using RMI to develop a distributed application involves these general steps:
1. Define a remote interface
2. Develop a servant that implements the interface
3. Develop a server that instantiates the servant and registers it at the Naming Service
4. Compile the interface, the servant and the server by javac.
5. Develop a client that gets a reference to the remote object and calls its remote methods.
6. Start the Naming service rmiregistry
7. Start the server on a server host, and run the client on a client host
Assume that processes in a distributed application are using RMI for interaction between each other. How can deadlock occur ? How to avoid it ?

In the local JVM case, the JVM can tell that the calling object "A" owns the lock and will allow the call back to "A" to proceed. In the distributed case, no such determination can be made, so the result is deadlock. Distributed objects behave differently than local objects. If you simply reuse a local implementation without handling locking and failure, you will probably get unpredictable results. Since remote method invocation on the same remote object may execute concurrently, a remote object implementation needs to make sure its implementation is thread-safe. For example when one client logs on to the server in order to maintain security and to avoid deadlock the same customer will not be allowed to logon to the server from another machine. This is done by creating Session Flag.
Name at least two RMI-related classes/interfaces, and shortly describe what each of those classes/interface is used for ?

1. java.rmi.Remote
- Interface that indicates interfaces whose methods may be invoked from a non-local JVM
2. java.rmi.Naming
- Class that is used to bind a name to an object and to lookup an object by name.
Explain two different ways, in which a Java RMI application executing in one JVM can obtain a reference to a remote object in another JMV without using rmiregistry. - RMIRegistry is used just for the bootstrapping purpose, nothing else. Once the client gets the stub object from the Registry, the Registry is not used anymore. The communication takes place directly between client and server by using sockets. So, if you can provide the bootstrapping in some other way, you can eliminate the use of Registry itself. In other words, if the client can get an object of the stub from the server somehow, that is just enough. That means if you have some facility to transport the stub object created in the server to the client machine (build a transport facility that is based on sockets that serialize the Stub object and sends it to the clients. That will eliminate the need of the Registry), you don't have to use the RMIRegistry or bind/rebind/lookup methods.
- RMI can be supported by using the Java Remote Method Protocol (JRMP) and the Internet Inter-ORB Protocol (IIOP). The JRMP is a specialized protocol designed for RMI; the IIOP is the standard protocol for communication between CORBA objects. RMI over IIOP allows Java remote objects to communicate with CORBA objects that might be written in a non-Java programming language.
- Some service providers, such as Sun's LDAP service provider, support the binding of java.rmi.Remote objects into directories. When java.rmi.Remote objects and/or RMI registries are bound into an enterprise-wide shared namespace such as the LDAP, RMI clients can look up java.rmi.Remote objects without knowing on which machine the objects are running.
java.rmi.RemoteExceptionA RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call.
java.rmi.NamingThe Naming class provides methods for storing and obtaining references to remote objects in the remote object registry.
java.rmi.server.UnicastRemoteObjectThe UnicastRemoteObject class defines a non-replicated remote object whose references are valid only while the server process is alive.
java.rmi.RemoteThe Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine.
java.rmi.NotBoundExceptionA NotBoundException is thrown if an attempt is made to lookup or unbind in the registry a name that has no associated binding.

Networking with Sockets and Java Message Service (JMS)

Question Answer
What do the follow three classes represent and what are they used for:
DatagramSocket is used by servers to listen for connection requests from clients specify a port to listen on, accept method starts to listen, blocks until a client requests a connection communication end point for interprocess communication over the network
Name and explain the meaning of three options or attributes (exluding IP addresses and port numbers) that can be set for a connecting socket object

List and briefly describe four programming concepts (abstractions) defined and used in Java Message Service (JMS) API.


Applets (Java SE) and MIDlets (Java ME)

Question Answer
Applet life cycleApplet life-cycle
– Notification methods of the Applet class:
• init(), start(), stop(), destroy()
– States of the applet:
• Loaded,stopped,started,destroyed
What is a Java applet ?
What are applets used for ?
How to make applets embedded in the same HTML page to interact with each other ?

Applet is java program that can be embedded into HTML pages. Java applets runs on the java enables web browsers such as mozila and internet explorer. Applet is designed to run remotely on the client browser.

Applets on the same Webpage share the Applet Context (JVM) and can interact with each other via
– Method invocation. The methods should be declared as synchronized.
– Static class variables;
– Piped connection.
• An applet gets reference to another applet by name.
What is a MIDlet?
Explain the MIDlet application model and the MIDlet life cycle (states and state transitions).

Explain what a ServerSocketConnection instance represents and what it is used for.Server Socket

• This interface defines the server socket stream connection.
• A server socket is accessed using a generic connection string with the host omitted.
• For example, socket://:79 defines an inbound server socket on port 79.
• The host can be discovered using the getLocalAddress() method.
• The acceptAndOpen() method returns a SocketConnection instance.
• Access to server socket connections may be restricted by the security policy of the device.
• must check access for the initial server socket connection and acceptAndOpen() must check before returning each new SocketConnection.
• A server socket can be used to dynamically select an available port by omitting both the host and the port parameters in the connection URL string.
• For example, socket:// defines an inbound server socket on a port which is allocated by the system.
• To discover the assigned port number use the getLocalPort() method.

Java Database Connectivity (JDBC) and Java Persistence API (JPA)

Question Answer
Explain meaning of each of the following four JDBC programming concepts and explain what each of the concepts is used for:
Datasource,Connection,Statement,Result Set

Data Source
- A database (DBMS), a file
- Pointed to by a URL of the form jdbc:<sub_protocol>:<datasource>
- Used to open a connection to a data source and to handle a connection, such as
com.pointbase.jdbc.jdbcUniversalDriver or sun.jdbc.odbc.JdbcOdbcDriver
- The driver class is either specified in the jdbc.drivers property or explicitly loaded by name, for example
Driver Manager
- Parses a given URL of a data source, look for a driver to handle the source and creates a connection to the source.
- A session with a data source. Used to create statements.
- Used to execute SQL statements (queries) -- an "envelope" for SQL
Prepared Statement
- A parameterized precompiled SQL statement (query)
Result set
- A data table returned as a result of execution of a SQL query -- an interface to inspect results of the SQL query
- Information about a data source (number of tables, etc.)
- Information about a table (number of columns, types, primary key, etc.)
- A set of operations (e.g. SQL statements) executed atomically.
- Should be committed or undone (rolled back)
- Auto commit of SQL statements on a connection is the JDBC default
- A transaction mode is controlled by special methods of the Connection object

Explain differences between JDBC and JPA

Java Database Connectivity (JDBC) is an API that allows developers to directly access a relational database. JPA is an approach to object persistence that aims to reduce the complexity of designing persistent applications.

Java Enterprise Technologies (Java EE)

Question Answer
What is Java servlet ? What are servlets used for ? What are HTTPServletRequest and HTTPServletResponse objects used for ?

Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. A servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface. The HttpServletRequest has methods that let you find out about incoming information such as FORM data, HTTP request headers, and the like. The HttpServletResponse has methods that lets you specify the HTTP response line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly, lets you obtain a PrintWriter used to send output back to the client.
What is a JSP ? What are the differences and similarites between JSPs and servlets ?
Which JSP constructs are used to create dynamic content ?

The view in a Java EE application
Written in HTML, translated to a Servlet by the container.
Dynamically-generated web content
– Communication with model written in Java
What is an Enterprise JavaBean (EJB)? Shortly decribe different types of EJBs. For each EJB type, explain when to use it and give an example.