Below are the points i wanted to share with readers of this tutorial.
I did not concentrate Non-Blocking IO as may be i could not understand properly.
1) A summary of the major elements of these changes from java 1.4 to java 1.5 is given below.
a) Replacement of the BufferedReader+InputStreamReader combination with the single Scanner class, with consequent erradication of the need to use the type 'wrapper' classes to convert String input into numeric values (a major improvement on the traditional method for obtaining input).
b) Associated with the above, replacement of the BufferedReader+FileReader combination with Scanner+File and that of the PrintWriter+FileWriter combination with PrintWriter+File for serial disc file I/O.
c) Replacement of the cumbersome addWindowListener(new WindowAdapter... method for closing down GUI applications with setDefaultCloseOperation(EXIT_ON_CLOSE). (This had been available since J2SE 1.3, but had deliberately not been included in the original text due to the earlier method being the one still used by most people at that time.)
d) The formatting of numeric output (particularly decimal output) via method printf.
e) The inclusion of generics in the declaration of Vectors, with the associated 'auto-boxing' and 'auto-unboxing' of elements.
f) Introduction of the 'enhanced for' loop where appropriate.
2) A port is a logical connection to a computer (as opposed to a physical connection)
and is identified by a number in the range 1-65535.Port numbers in the range 1-1023 are normally set aside for the use of specified standard services, often referred to as 'well-known' services. For example, port 80 is normally used by Web servers.
3) For each port supplying a service, there is a server program waiting for any requests. All such programs run together in parallel on the host machine. When a client attempts to make connection with a particular server program, it supplies the port number of the associated service. The host machine examines the port number and passes the client’s transmission to the appropriate server program for processing.
4) In common with all modern computer networks, the Internet is a packet-switched network, which means that messages between computers on the Internet are broken up into blocks of information called packets, with each packet being handled separately and possibly travelling by a completely different route from that of other
such packets from the same message. IP is concerned with the routing of these packets through an internet.However, since packets could still arrive out of sequence, be corrupted or even not arrive at all (without indication to either sender or intended recipient that anything had gone wrong), it was decided to place another protocol layer on top of IP. This further layer was provided by TCP (Transmission Control Protocol), which allowed each end of a connection to acknowledge receipt of IP packets and/or
request retransmission of lost or corrupted packets.
5) UDP is an unreliable protocol, since:
• it doesn't guarantee that each packet will arrive;
• it doesn't guarantee that packets will be in the right order.
However, it is significantly faster than TCP.
6) Below is one example of Simple Socket Program using Server Socket and Client Socket
package tcp;
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPEchoClient {
private static InetAddress host;
private static final int PORT = 1234;
public static void main(String[] args) {
try
{
host = InetAddress.getLocalHost();
}
catch(UnknownHostException uhEx)
{
System.out.println("Host ID not found!");
System.exit(1);
}
accessServer();
}
private static void accessServer()
{
Socket link = null; //Step 1.
try
{
link =new Socket(host,PORT); //Step 1.
Scanner input = new Scanner(link.getInputStream()); //Step 2.
PrintWriter output =new PrintWriter(link.getOutputStream(),true); //Step 2.
// Set up stream for keyboard entry...
String message, response;
String strArr[]={"Demo","India","UK","***CLOSE***"};
int i=0;
do
{
message = strArr[i];
output.println(message); //Step 3.
response = input.nextLine(); //Step 3.
System.out.println("\nSERVER> "+response);
i++;
}while (!message.equals("***CLOSE***"));
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
try
{
System.out.println("\n* Closing connection... *");
link.close(); //Step 4.
}
catch(IOException ioEx)
{
System.out.println(
"Unable to disconnect!");
System.exit(1);
}
}
}
}
package tcp;
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPEchoServer {
private static ServerSocket servSock;
private static final int PORT = 1234;
public static void main(String[] args) {
System.out.println("Opening port...\n");
try
{
servSock = new ServerSocket(PORT); //Step 1.
}
catch(IOException ioEx)
{
System.out.println("Unable to attach to port!");
System.exit(1);
}
do
{
handleClient();
}while (true);
}
private static void handleClient() {
Socket link = null; //Step 2.
try {
link = servSock.accept(); //Step 2.
Scanner input = new Scanner(link.getInputStream());//Step 3.
PrintWriter output = new PrintWriter(link.getOutputStream(),true); //Step 3.
int numMessages = 0;
String message = input.nextLine(); //Step 4.
while (!message.equals("***CLOSE***")) {
System.out.println("Message received.");
numMessages++;
output.println("Message " + numMessages + ": " + message); //Step 4.
message = input.nextLine();
}
output.println(numMessages + " messages received.");//Step 4.
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
try
{
System.out.println("\n* Closing connection... *");
link.close(); //Step 5.
System.exit(1);
}
catch(IOException ioEx)
{
System.out.println("Unable to disconnect!");
System.exit(1);
}
}
}
}
7) Unlike TCP/IP sockets, datagram sockets are connectionless.A further difference from TCP/IP sockets is that, instead of a ServerSocket object, the server creates a DatagramSocket object, as does each client when it wants to send datagram(s) to the server. The final and most significant difference is that
DatagramPacket objects are created and sent at both ends, rather than simple strings.
8) Below is one example using UDP protocol.
package udp;
import java.io.*;
import java.net.*;
import java.util.*;
public class UDPEchoClient {
private static InetAddress host;
private static final int PORT = 1234;
private static DatagramSocket datagramSocket;
private static DatagramPacket inPacket, outPacket;
private static byte[] buffer;
public static void main(String[] args) {
try
{
host = InetAddress.getLocalHost();
}
catch(UnknownHostException uhEx)
{
System.out.println("Host ID not found!");
System.exit(1);
}
accessServer();
}
private static void accessServer() {
try
{
// Step 1...
datagramSocket = new DatagramSocket();
// Set up stream for keyboard entry...
Scanner userEntry = new Scanner(System.in);
String message="", response="";
do
{
System.out.print("Enter message: ");
message = userEntry.nextLine();
if (!message.equals("***CLOSE***")) {
outPacket = new DatagramPacket(message.getBytes(),message.length(),host,PORT); //Step 2.
// Step 3...
datagramSocket.send(outPacket);
buffer = new byte[256]; //Step 4.
inPacket =new DatagramPacket(buffer, buffer.length);//Step 5.
// Step 6...
datagramSocket.receive(inPacket);
response =new String(inPacket.getData(),0, inPacket.getLength()); //Step 7.
System.out.println("\nSERVER> "+response);
}
}while (!message.equals("***CLOSE***"));
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
System.out.println(
"\n* Closing connection... *");
datagramSocket.close(); //Step 8.
}
}
}
package udp;
import java.io.*;
import java.net.*;
public class UDPEchoServer {
private static final int PORT = 1234;
private static DatagramSocket datagramSocket;
private static DatagramPacket inPacket, outPacket;
private static byte[] buffer;
public static void main(String[] args) {
System.out.println("Opening port...\n");
try
{
datagramSocket = new DatagramSocket(PORT); //Step 1.
}
catch(SocketException sockEx)
{
System.out.println("Unable to attach to port!");
System.exit(1);
}
handleClient();
}
private static void handleClient() {
try
{
String messageIn,messageOut;
int numMessages = 0;
do
{
buffer = new byte[256]; //Step 2.
inPacket =new DatagramPacket(buffer, buffer.length); //Step 3.
datagramSocket.receive(inPacket);//Step 4.
InetAddress clientAddress =inPacket.getAddress(); //Step 5.
int clientPort =inPacket.getPort(); //Step 5.
messageIn = new String(inPacket.getData(),0,inPacket.getLength()); //Step 6.
System.out.println("Message received.");
numMessages++;
messageOut = "Message " + numMessages + ": " + messageIn;
outPacket = new DatagramPacket(messageOut.getBytes(),messageOut.length(),clientAddress,clientPort); //Step 7.
datagramSocket.send(outPacket); //Step 8.
}while (true);
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally //If exception thrown, close connection.
{
System.out.println(
"\n* Closing connection... *");
datagramSocket.close(); //Step 9.
}
}
}
9) A thread is a flow of control through a program.Unlike a process, a thread does not have a separate allocation of memory, but shares memory with other threads created by the same application.Of course, unless we have a multiprocessor system, it is not possible to have more than one task being executed simultaneously. The operating system, then, must have some strategy for determining which thread is to be given use of the processor at any given time. On PCs, threads with the same priority are each given an equal timeslice or time quantum for execution on the processor. When the quantum expires,the first thread is suspended and the next thread in the queue is given the processor, and so on. If some threads require more urgent attention than others, then they may be assigned higher priorities (allowing pre-emption to occur). Under the Solaris operating system, a thread runs either to completion or until another higher-priority thread becomes ready. If the latter occurs first, then the second thread pre-empts the first and is given control of the processor. For threads with the same priority, timeslicing is used, so that a thread does not have to wait for another thread with the same priority to end.
10) If a thread executing a synchronized method determines that it cannot proceed,then it may put itself into a waiting state by calling method wait.Methods wait, notify and notifyAll may only be called when the current thread has a lock on the object (i.e., from within a synchronized method or from within a method that has been called by a synchronized method). If any of these methods is called from elsewhere, an IllegalMonitorStateException is thrown.
11) Serial access files are simple to handle and are quite widely used in small-scale applications or as a means of providing temporary storage in larger-scale applications. However, they do have two distinct disadvantages, as noted below.
(i) We can't go directly to a specific record. In order to access a particular record,it is necessary to physically read past all the preceding records. For applications containing thousands of records, this is simply not feasible.
(ii) It is not possible to add or modify records within an existing file. (The whole file would have to be re-created!)
12)
Random access files (probably more meaningfully called direct access files) overcome both of these problems, but do have some disadvantages of their own...
(i) In common usage, all the (logical) records in a particular file must be of the
same length.
(ii) Again in common usage, a given string field must be of the same length for all
records on the file.
(iii) Numeric data is not in human-readable form.
13) RMI Security: If both the client and server processes have direct access to the same class files, then there is no need to take special security precautions, since no security holes can be opened up by such an arrangement. However, an application receiving an object for which it does not have the corresponding class file can try to load that class file from a remote location and instantiate the object in its JVM. Unfortunately, an object passed as an RMI argument from such a remote source can attempt to initiate execution on the client's machine immediately upon deserialisation without the user/programmer doing anything with it! Such a security breach is not permitted to occur, of course. The loading of this file is handled by an object of class SecureClassLoader, which must have security restrictions defined for it. File java.policy defines these security restrictions, while file java.security defines the security properties. Implementation of the security policy is controlled by an object of class RMISecurityManager (a subclass of SecurityManager). The RMISecurityManager creates the same 'sandbox' rules that govern applets. Without such an object, a Java application will not even attempt to load classes that are not from its local file system.
14) RMI is a powerful mechanism for distributing and processing objects in a platform-independent manner, it has one significant drawback it only works with objects that have been created using Java.
15) A servlet is a program written in Java that runs on a Web server.It is executed in response to a client's (i.e., a browser's) HTTP request and creates a document (usually an HTML document) to be returned to the client by the server.
16) Implicit JSP Objects
| Variable | Type | Purpose |
|---|---|---|
| request | HttpServletRequest | Http request originally sent to server. |
| response | HttpServletResponse | Http response to request. |
| session | HttpSession | Session object associated with the above request and response. |
| application | ServletContext | Holds references to other objects that more than one user may access, such as a database link. |
| out | JspWriter | Object that writes to the response output stream. |
| exception | Throwable | Contains information about a runtime error and is available only on error pages. |
| pageContext | PageContext | Encapsulates the page context. |
| config | ServletConfig | ServletConfig object for this JSP. |
| page | Object | The this object reference in this JSP. |
Table of Contents
Basic Concepts, Protocols and Terminology
Starting Network Programming in Java
Multithreading
File Handling
Remote Method Invocation (RMI)
CORBA
Java Database Connectivity (JDBC)
Servlets
JavaServer Pages (JSPs)
JavaBeans
Introduction to Enterprise JavaBeans
Multimedia
Applets
Appendix A Structured Query Language (SQL)
Appendix B Deployment Descriptors
Index
About the Author
Jan Graba is a Senior Lecturer in Software Engineering at Sheffield Hallam University, where he has specialised in the teaching of network programming with Java for the past five years.
Hope you enjoy reading this book.
No comments:
Post a Comment