Download Socket

Document related concepts
no text concepts found
Transcript
JSP
1
Socket Programming Concept
Socket:
a host-local, application-created/owned, OS-controlled
interface (a “door”) into which application process can
both send and receive messages to/from another (remote or
local) application process
explicitly created, used, released by apps
client/server paradigm (so-called client-server programming)
two types of transport service via socket API:
• unreliable datagram (UDP)
• reliable, byte stream-oriented (TCP)
Introduced in BSD 4.1 UNIX (1981)
(Berkeley Software Distribution)
JSP
2
Socket Programming with TCP
Host (client)
process
Host (server)
Controlled by
Application developer
socket
TCP resources
(buffers, variables)
Knocking on
the door . . .
(by IP addr.
and port #) Virtual
JSP
process
socket ~ a door
Controlled by
Operating system
Internet
TCP resources
(buffers, variables)
While server
process is running
(ready)
pipe
3
Sockets -- Client, Welcoming, and connection
send Z
arbitrary
bytes
into
socket
TCP connection’s
X
Y
[
^
]
\
after Y ~ \
process
process
JSP
after Y ~ \
Can be more …
4
Socket programming with TCP (cont’d)
Client must contact server but…
server process must first be
running
server must have created
socket (door) that welcomes
client’s contact
Client contacts server by…
creating client-local TCP
socket
specifying IP address, port
number of server process
JSP
When client creates socket: client
TCP establishes connection to
server TCP
When contacted by client, server
TCP creates new socket for
server process to communicate
with client
• To allows server to talk with
multiple clients
application viewpoint
TCP provides reliable, in-order
transfer of bytes (“pipe”)
between client and server
5
Client/Server
(Win)socket
interaction
|
TCP
JSP
6
Berkeley (BSD)/Winsocket API
Accept()
接受client端的連結要求,建立連接
Bind()
指定socket的本地IP位址及port number(TCP/UDP)
Closesocket()
關閉本機socket以結束連線
Connet()
要求和遠方/對方通訊端點連線,通常用於client端
Getpeername() 取得連接遠端主機(對方)的socket位址
Getsockname() 得到本地主機的socket位址
JSP
Getsockopt()
得到socket的選項值
Ioctlsock()
設定或得到socket的操作參數
Listen()
設定socket為「監聽」連接狀態,準備接受來自client端的connect request
Recv()
由已連接的遠端socket接收資料
recvfrom()
由socket接收傳來的遠端(發送者)主機資料其位址
select()
決定一個或多個的socket的讀、寫、或錯誤的狀態,讓使用者能同時處理數個
socket的I/O,達到多工的功能
send()
傳送資料到已連接的socket(即通訊對方)
sendto()
傳送資料到指定的主機號碼和port number(遠端點)
setsockopt()
設定本機的socket選項
shutdown()
關閉socket的傳送與接收
socket()
建立一個新的socket(稱其為socket descriptor或socket ID)
7
Java Networking Basis
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.
The java.net package provides two classes . . .
Socket ~ implement the client side of the connection
ServerSocket ~ implement the server side of the connection
Datagram
is an independent, self-contained message sent over the
network whose arrival, arrival time, and content are not
guaranteed.
JSP
8
Java Networking Basis
When processes communicate over a network, Java
technology uses its streams model. A socket can hold two
streams: one input stream and one output stream.
A process sends data to another process through the network
by writing to the output stream associated with the socket.
A process reads data written by another process by reading
from the input stream associated with the socket.
When making a network connection, you need to
know the address or the name of the remote machine
network connection requires a port number (0 ~ 65535)
TCP/IP socket connections are implemented with classes
in the java.net package.
JSP
9
JAVA TCP Socket Connection Model
TCP socket connections are implemented
with classes in the java.net package.
• TCP/IP server applications rely on the ServerSocket and Socket
networking classes provided by the Java programming language. The
ServerSocket class takes most of the work out of establishing a server.
JSP
10
JAVA Client/Server socket interaction: TCP
Server (running on hostid)
Client
create socket,
port=x, for
incoming request:
welcomeSocket =
ServerSocket()
TCP
wait for incoming
connection
connection request
setup
connectionSocket =
welcomeSocket.accept()
read request from
connectionSocket
write reply to
connectionSocket
close
connectionSocket
JSP
create socket,
connect to hostid, port=x
clientSocket = Socket()
send request using
clientSocket
read reply from
clientSocket
close
clientSocket
11
JAVA Socket Programming with TCP
JSP
process
keyboard
inFromUser
iinFromServer
server reads line from socket
server converts line to
uppercase, sends back to
client
client reads, prints modified
line from socket
(inFromServer stream)
Input stream: sequence of bytes
into process
Output stream: sequence of bytes
out of process
outToServer
Example client-server app:
client reads line from
standard input
(inFromUser stream) ,
sends to server via socket
(outToServer stream)
client socket
12
TCP Client/Server Example
JSP
Operation:
client reads a line from its standard input (keyboard) and sends
the line out its socket to the server.
server reads a line from its connection socket.
server converts the line to uppercase.
server sends the modified line out its connection socket to the
client.
client reads the modified line from its socket and prints the line
on its standard output (monitor).
To test the program pair:
execute TCPServer.class, the compiled server program, in the
server
then execute TCPClient.class, the compiled client program, in
the client. This creates a process in the client and establishes a
TCP connection
to use the application, you type a sentence followed by a
carriage return, then see what happen?
13
Example: Java client (TCP)
Starting
point
import java.io.*;
import java.net.*; Program name (source code .java)
class TCPClient
{
public static void main(String argv[]) throws Exception
{
String sentence;
declare objects of type String
String modifiedSentence;
initialized with System.in
Create BufferedReader inFromUser = new
input stream BufferedReader(new InputStreamReader(System.in));
Create
client socket, Socket clientSocket = new Socket("hostname", 6789);
connect to server
Create DataOutputStream outToServer = new
output stream
DataOutputStream(clientSocket.getOutputStream());
attached
to socket
JSP
14
Example: Java (TCP) client (cont’d)
Create BufferedReader inFromServer = new
input stream BufferedReader(new
attached to InputStreamReader(clientSocket.getInputStream()));
socket
sentence = inFromUser.readLine();
Send line
outToServer.writeBytes(sentence + '\n');
to server
Read line modifiedSentence = inFromServer.readLine();
from server
System.out.println("FROM SERVER:" + modifiedSentence);
Close
TCP conn. clientSocket.close();
}
}
JSP
15
Example: Java server (TCP)
import java.io.*;
import java.net.*;
ServerSocket class takes most of
the work out of establishing a server.
class TCPServer
{
public static void main(String argv[]) throws Exception
{
String clientSentence;
Create welcoming socket
String capitalizedSentence;
at port 6789
ServerSocket welcomeSocket = new ServerSocket(6789);
Wait, on welcoming socket
while(true)
for contact by client
{
Socket connectionSocket = welcomeSocket.accept();
Create input stream,
BufferedReader inFromClient =
attached to socket
new BufferedReader(new
InputStreamReader(connectionSocket.getInputStream()));
JSP
16
Example: Java (TCP) server (cont’d)
Create output stream,
attached to socket
DataOutputStream outToClient =
new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
Read in line
from socket
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
Write out line
to socket
}
}
}
JSP
End of while loop,
loop back and wait for
another client connection
17
Testing on your PC
• Server site: (open a MS-DOS window)
• Client site:
(open another MS-DOS window and type in a lower-case string)
Reply from server – all are converted into upper-case characters
JSP
18
Socket programming with UDP
UDP: no “connection”
between client and server
no handshaking
sender explicitly attaches
IP address and port of
destination
server must extract IP
address, port of sender
from received datagram
application viewpoint
UDP provides unreliable transfer
of groups of bytes (“datagrams”)
between client and server
UDP: transmitted data may
be received out of order, or
lost
JSP
19
Client/server socket interaction: UDP
Server
Client
socket()
socket()
bind()
recvfrom()
sendto()
sendto()
recvfrom()
closesocket()
closesocket()
• Connectionless
JSP
no clear client/server relation
one way
20
JAVA UDP Socket
The User Datagram Protocol is supported through two
classes:
DatagramSocket and DatagramPacket
The packet is a self-contained message that includes
information about the sender, the length of the message,
and the message itself.
DatagramPacket has two constructors: one for receiving data
and one for sending data:
DatagramPacket (byte[] recvBuf, int readLength)
• Used to set up a byte array to receive a UDP packet.
DatagramPacket (byte[] sendBuf, int sendLength,
InetAddress iaddr, int iport)
• Used to set up a UDP packet for transmission.
JSP
21
UDP Socket (cont’d)
DatagramSocket is used to read and write UDP packets.
This class has three constructors (allow you to specify the
port and internet address to which to bind:)
DatagramSocket()
Binds to any available port on the local host
DatagramSocket(int port)
Binds to the specified port on the local host
DatagramSocket(int port, InetAddress iaddr)
Binds to the specified port on the specified address
JSP
22
Client/server socket interaction: UDP
Server (running on hostid)
create socket,
port=x, for
incoming request:
serverSocket =
DatagramSocket()
read request from
serverSocket
write reply to
serverSocket
specifying client
host address,
port umber
JSP
Client
create socket,
clientSocket =
DatagramSocket()
Create, address (hostid,port=x)
send datagram request
using clientSocket
read reply from
clientSocket
close
clientSocket
23
UDP
|
Client/Server
Example
Client process
keyboard
Server process
JSP
24
Example: Java client (UDP)
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
Create input stream
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
Create client socket
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("hostname");
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
JSP
Translate hostname to IP
address using DNS
String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
25
Example: Java (UDP) client (cont’d)
DatagramPacket sendPacket =
Create datagram with data-tosend, length, IP addr, port
new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
Send datagram to server
DatagramPacket receivePacket =
new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
Read datagram from server
String modifiedSentence =
new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
JSP
}
26
Example: Java server (UDP)
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
Create datagram socket
{
at port 9876
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)
{
JSP
Create space for
received datagram
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
Receive datagram
27
Example: Java (UDP) server (cont’d)
String sentence = new String(receivePacket.getData());
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
Get IP addr, port #,
of sender
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
Create datagram
to send to client
DatagramPacket sendPacket = new
DatagramPacket(sendData, sendData.length, IPAddress,
port);
Write out datagram
to socket
serverSocket.send(sendPacket);
}
}
JSP
}
End of while loop, loop back and
wait for another datagram
28
JAVA Programming
Programming Basis
Basis
JAVA
(A supplementary to the Java Socket Programming)
JSP
29
What is Java Programming Language ?
The Java programming language is:
A programming language
A development environment
An application environment
The Java technology architecture uses the following
features to fulfill the primary goals:
The Java virtual machine (JVM)
Garbage collection ~ no memory leaks
Code security
JSP
30
JVM
An imaginary machine that is implemented by emulating it in
software on a real machine. Code for the Java Virtual Machine
is stored in .class files, each of which contains code for at most
one public class.
JVM specification enables Java software to be platform
independent because the compilation is done for a generic
machine
generic machine (aka) JVM emulate this “generic machine”
in software to run on various existing computer systems or
implemented in hardware.
JSP
31
JVM (cont’d)
The compiler takes the Java application source code and
generates bytecodes.
Bytecodes are machine code instructions for the JVM.
Every Java interpreter, regardless of whether it is a Java
technology development tool or a Web browser that can run
applets, has an implementation of the JVM.
Any compliant Java technology interpreter must be able to
run any program with class files that conform to the class file
format specified in The Java Virtual Machine Specification.
JSP
32
Garbage Collection
JSP
Once the allocated memory is no longer required (the pointer that
references the memory has gone out of scope), the program or
runtime environment should deallocate the memory. In C, C++,
and other languages, the program developer is responsible for
deallocating the memory.
The Java programming language removes the responsibility for
deallocating memory from the programmer.
It provides a system-level thread that tracks each memory
allocation. During idle cycles in the Java virtual machine, the
garbage collection thread checks for and frees any memory that
can be freed.
Garbage collection happens automatically during the lifetime of a
Java technology program, eliminating the need to deallocate
memory and avoiding memory leaks. However, garbage
collection schemes can vary dramatically across JVM
implementations.
33
JAVA Application Environment and Security
√
(machine-indep.
bytecodes)
(JIT ~ Just-In-Time)
JSP
34
JAES (cont’d)
A Java technology runtime environment runs code compiled for a
JVM and performs three main tasks:
Loads code – Performed by the class loader
Verifies code – Performed by the bytecode verifier
Executes code – Performed by the runtime interpreter
Class Loader
It loads all classes needed for the execution of a program.
The class loader adds security by separating the name
spaces for the classes of the local file system from those
imported from network sources. This limits any Trojan horse
applications because local classes are always loaded first.
Bytecode Verifier
Tests the format of code fragments and checks code
fragments for illegal code (that forges pointers, violates
access rights on objects, or attempts to change object type.)
JSP
35
JAES (cont’d)
JIT (Just-In-Time) code generator
In some Java technology runtime environments, a portion of
the verified bytecode is compiled to native machine code and
executed directly on the hardware platform.
This allows Java software code to run close to the speed of C
or C++ with a small delay at loadtime to allow compilation to
the native machine code.
JSP
36
JAVA – an Overview
☺
JSP
37
Object-Oriented Programming Concepts
JSP
What is an Object?
a software bundle of related variables and methods.
Software objects are often used to model real-world objects
you find in everyday life.
What is a Message?
Software objects interact and communicate with each other
using messages.
What is a Class?
A class is a blueprint or prototype that defines the variables
and the methods common to all objects of a certain kind.
have many objects of the same kind that share characteristics
What is a Method?
Methods are similar to the functions or procedures in
languages such as C.
38
Object-Oriented Programming Concepts
What is Inheritance?
A class inherits state and behavior from its superclass.
Inheritance provides a powerful and natural mechanism for
organizing and structuring software programs.
What is an Interface?
JSP
An interface is a contract in the form of a collection of method
and constant declarations. When a class implements an
interface, it promises to implement all of the methods declared
in that interface. Within the Java programming language, an
interface is a device that unrelated objects use to interact
with each other. An interface is probably most analogous to a
protocol (an agreed on behavior). In fact, other object-oriented
languages have the functionality of interfaces, but they call
their interfaces protocols.
39
Classes and Packages - Introduction
JSP
Class ~ a generic term for a module that provides functionality
Java Development Kit comes with a standard set of classes class library that implements most of the basic behaviors
needed—not only for programming tasks (for example, classes
to provide basic math functions, arrays, and strings), but also
for graphics and networking.
package ~ a group of related classes
The class library is organized into many packages, each
containing several classes.
Prominent packages :
java.lang ~ contains classes that form the core of the language,
such as String, Math, Integer, and Thread.
java.awt ~ contains classes that make up the Abstract Window
Toolkit (AWT). This package is used for
constructing and managing the graphical user
interface of the application.
40
Classes and Packages – Introduction (Cont’d)
java.applet ~ contains classes that provide applet-specific
behavior.
java.net ~ contains classes for performing network related
operations and dealing with sockets and uniform
resource locators (URLs).
java.io ~ contains classes that deal with file I/O.
java.util ~ contains utility classes for tasks, such as random
number generation, defining system properties, and
using date and calendar related functions.
For more . . .
Refer to JAVA API Document (a set of HTML files)
JSP
41
JAVA API Documents
Double click
JSP
42
Java.io API Package
JSP
43
Java.io API (cont’d)
JSP
44
Java.io API (cont’d)
JSP
45
Java Programming Rules and Conventions
Java is case sensitive. Keywords are written entirely in lowercase.
JSP
“//…” ~ single line comments; “/*…/*” ~ multiple lines comments.
Statements must end with a “ ; ” . A group of statements placed
between “{ }” is called code block (include class and methods.)
Identifier ~ a name you assign
corresponding to a location in
memory. The 1st char must be one of the following: A-Z, a-z, “_”,
and “$”. The 2nd char: Any char in above and 0-9.
46
Java Programming Rules and Conventions
JSP
Naming convention:
Class ~ written as a sequence of descriptive words (nouns) and
starts with the first letter of each word capitalized.
• Ex: Class CalssTwo ();
Interface ~ should be capticalized like class names.
• Ex: interface Account;
Variable ~ Same as above but must begin with an lowecase.
Words are separated by Capital letter. No underscord and “$”.
• Ex: int variableOne;
Constant ~ Primitive constant should be all upper-case words and
use “_” between each word; Object constant can use mixed case.
• Ex: final int CONSTANT_ONE = 37;
Method ~ same as variable except the phrase usually constants a
verb, capital letters separate words, and always ends with a set of
“{}”.
• Ex: int methodOne();
47
A Basic Java Application
Java Application ~ a Java program that executes independently
of a browser
Java Applet ~ a Java program to be included in HTML pages
and executed in Java-enabled browsers.
One minimum application – displays/prints the string
Hello World! on the screen.
JSP
1
2
3
4
5
6
7
8
9
10
//
// Sample HelloWorld application
//
public class HelloWorldApp
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
Lines 1–3 are
comment lines
HelloWorldApp.java
(source code)
48
HelloWorldApp.java Explained
1
2
3
//
// Sample HelloWorld application
//
4
public class HelloWorldApp
5 {
6
public static void main (String args[])
7
{
8
System.out.println("Hello World!");
9
}
10 }
Line 4 ~ declares the class-name as HelloWorldApp.
HelloWorldApp
A class name specified in a source file creates a classname.class
file in the same directory as the source code. In this case, the
compiler creates a file called HelloWorldApp.class.
HelloWorldApp.class contains the compiled code for the public
class HelloWorldApp.
JSP
49
HelloWorldApp.java Explained
1
2
3
4
5
6
//
// Sample HelloWorld application
//
public class HelloWorldApp
{
public static void main (String args[])
7
{
8
System.out.println("Hello World!");
9
}
10 }
JSP
Line 6 ~ the main() method declaration that the execution of the
program starts.
The Java technology interpreter must find this defined exactly as
given or it will refuse to run the program.
If the program is given any arguments on its command line,
these are passed into the main() method, in an array of String
called args.
50
HelloWorldApp.java Explained
public ~ The method main() can be accessed by anything,
including the Java technology interpreter.
static ~ This keyword tells the compiler that the main() method is
usable in the context of the class HelloWorldApp and
should be run before the program does anything else.
void ~ Indicates that the method main() does not return anything.
This is important because the Java programming language
performs careful type checking to confirm that the methods
called return the types with which they were declared.
String args[] ~ The declaration of a String array. Contains
arguments typed on the command line following
the class name.
For example:
java HelloWorldApp args[0] args[1] . . .
JSP
51
HelloWorldApp.java Explained
1
2
3
4
5
6
7
8
9
10
//
// Sample HelloWorld application
//
public class HelloWorldApp
{
public static void main (String args[])
{
System.out.println("Hello World!");
}
}
Line 8 ~ illustrates the use of a class name, an object name, and a
method call.
It prints the string “Hello World!” to the standard output using
the println() method of the PrintStream out object, referenced by
the out field of the System class.
JSP
52
HelloWorldApp.java Explained
The static variable out is defined in the System class to be of
type PrintStream; PrintStream is a class defined in the java.io
package, and the source file is called PrintStream.java . This is
where the println method is declared.
The println() method in this example takes a string argument
and writes it to the standard output stream.
Lines 9-10 ~ the two braces, close the method main() and the
class HelloWorldApp, respectively.
JSP
53
Compiling and Running the HelloWorldApp.java
Once you have created the HelloWorldApp.java source file . . .
Compile it :
javac HelloWorldApp.java
If the compiler does not return any messages, the new file
HelloWorldApp.class is stored in the same directory as the
source file, unless specified otherwise.
Run your HelloWorldApp application :
(use interpreter : java)
java HelloWorldApp
Hello World!
JSP
Note – The PATH environment variable must be set to find
java and javac; e.g., SET PATH=c:\jdk1.4\bin
54
Another Example
import java.lang.*; //引用套件
public class Hello_Java
{
public static void main(String args[])
{
Printer My_Printer = new Printer();
物件之動態特性(模擬)
//依據Printer類別建立My_Printer物件
My_Printer.Hello(); // 呼叫My_Printer物件的方法 – Hello()
}
物件方法之存取:物件變數.方法名稱(引數列)
object method argument
}
class Printer //定義Printer類別(class)
物件之靜態特性(模擬)
{
private int Serial_Number; //定義Printer類別的屬性(attribute)
屬性
物件屬性之存取:物件變數.屬性名稱
Return type
name
public void Hello() //定義Printer類別的方法(method)
{
System.out.println("Hello Java!"); //印出Hello Java!
}
// add other methods hereafter.
}
JSP
55
Exception
What is an exception ? ( In the Java programming language)
the Exception class defines mild error conditions that your
programs might encounter.
Rather than letting the program terminate, you can write code
to handle your exceptions and continue program execution.
Any abnormal condition that disturbs the normal program flow
while the program is in execution is an error or exception.
Exceptions can occur when:
The file you try to open does not exist
The network connection is disrupted
Operands being manipulated are out of prescribed ranges
The class file that you are interested in loading is missing
JSP
56
Call Stack Mechanism
If a statement within a method throws an exception, that
exception is thrown to the calling method. If the exception is not
handled in the calling method also, it is thrown to the caller of
that method. This process continues until the exception is
handled.
If an exception is not handled by the time it gets back to main()
and main() does not handle it, the exception terminates the
program abnormally.
Example:
The main() method calls another method named first(), and
this in turn calls another method named second(). If an
exception occurs in second(), it is thrown back to first(),
where a check is made to see if there is a catch for that type
of exception. If no catch exists in first(), the next method in
the call stack, main(), is checked. If the exception is not
handled by the last method on the call stack, then a runtime
error occurs and the program stops executing.
JSP
57
Exception Example
This program quickly
produces an exception. Where
the exception comes from ?
Exception produced :
ArrayIndexOutOfBoundsEx
ception
in the System.out.println
method when i has a value
of 3.
JSP
1 public class HelloWorld {
2 public static void main (String args[]) {
3 int i = 0;
4
5 String greetings [] = {
6 "Hello world!",
7 "No, I mean it!",
8 "HELLO WORLD!!"
9 };
10
11 while (i < 4) {
12 System.out.println (greetings[i]);
13 i++;
14 }
15 }
16 }
58
Exception Handling
Exception handling allows a program to catch exceptions,
handle them, and then continue program execution.
“throw” an exception back to its caller (upper level), to signal
that a problem has occurred. The calling method catch the
thrown exception and recovers from it if possible.
JSP
59
Try and Catch statement
try block and create a list of adjoining catch blocks, one for
each possible exception that can be thrown. The block statement
of a catch clause is executed if the exception generated matches
the one listed in the catch.
The try statement governs the statements enclosed within it and
defines the scope of any exception handlers associated with it.
JSP
1 try {
2 // code that might throw a particular exception
3 }
try statements can be nested;
the exceptions can migrate upward.
4 catch (MyExceptionType e) {
5 // code to execute if a MyExceptionType exception is
thrown
6 }
7 catch (Exception e) {
8 // code to execute if a general Exception exception is thrown
9}
60
More on catch statement
You associate exception handlers with a try statement by
providing one or more catch blocks directly after the try block.
catch (SomeThrowableObject variableName) {
Java statements
variableName is the name by which
}
the handler can refer to the exception
caught by the handler.
Exception's declared name
JSP
e
The argument to the catch statement looks like an argument
declaration for a method. The argument type,
SomeThrowableObject, declares the type of exception that the
handler can handle and must be the name of a class that inherits
from the Throwable class defined in the java.lang package.
When Java programs throw an exception, they are really just
throwing an object, and only objects that derive from
Throwable can be thrown.
61
Finally statement
finally Statement
The finally statement defines a block of code that always
executes, regardless of whether an exception was caught.
(a must-do)
1 try {
2 startFaucet();
3 waterLawn();
4}
5 finally {
6 stopFaucet();
7}
JSP
• A try statement must be accompanied by at least one catch
block or one finally block. Use of catch() is optional,
depending on the situation
62
Exceptionhandling
Example
Result:
Hello world!
This is always printed
No, I mean it!
This is always printed
HELLO WORLD!!
This is always printed
Re-setting Index Value
This is always printed
JSP
1 public class HelloWorld {
2 public static void main (String args[]) {
3 int i = 0;
4 String greetings [] = {
5 "Hello world!",
6 "No, I mean it!",
7 "HELLO WORLD!!"
8 };
9
10 while (i < 4) {
11 try {
12 System.out.println (greetings[i]);
13 }
14 catch (ArrayIndexOutOfBoundsException e){
15 System.out.println("Re-stting Index Value");
16 i = -1;
exception is caught and
17
18
19
20
21
the array index is reset
} finally {
System.out.println("This is always printed");
}
i++;
} } }
63
Declare Rule for Exception
(w/o handling)
If an Exception (which differs from an Error or RuntimeException)
occurs while a method is on the stack (that is, it has been called),
then the caller of that method must determine what action is to be
taken if a problem arises.
The programmer can do the following to satisfy this requirement:
To have the calling method handle the exception by including
in its code a try {} catch(){} block where the catch names any
superclass of the thrown exception.
To have the calling method indicate that it does not handle the
exception, and that the exception will be thrown back to its
calling method. This is done by marking the calling
method’s declaration with a throws clause as follows:
(, . . . for more)
public void callsTroublesome() throws IOException
JSP
64
Exception Categories
There are three broad categories of exceptions: Error,
RuntimeException, and Exception.
The class java.lang.Throwable acts as the parent class for all
objects that can be thrown and caught using the exceptionhandling mechanisms. Methods defined in the Throwable class
retrieve the error message associated with the exception and print
the stack trace showing where the exception occurred.
subclasses
JSP
65
Stream I/O
A stream is either a source of or a destination for bytes.
To bring in information, a program opens a stream on an information
source (a file, memory, a socket) and reads the information
sequentially.
read
A program can send information to an external destination by opening
a stream to a destination and writing the information out sequentially
write
Write while more info
The java.io package contains a collection of stream classes that
support these algorithms for reading and writing.
JSP
66
Four Stream Types
X
Y
Z
[
JSP
Two basic streams:
To read bytes from an input stream,
Input stream
there must be a source of characters
Output stream
associated with the stream.
Node stream
they read from or write to a specific place, such as a disk file
or an area of memory.
Node InputStream
(e.g., from a file)
FilterInputStream
Filter stream
A filter input stream is created with a connection to an
existing input stream.
67
Character Stream
Reader provides the API and partial implementation for readers-streams that read 16-bit characters
Writer provides the API and partial implementation for writers-streams that write 16-bit characters.
abstract
Super-classes
JSP
68
Byte Stream
To read and write 8-bit bytes, programs should use the byte
streams, descendants of InputStream and OutputStream .
Both Streams provide the API and partial implementation for
input streams (streams that read 8-bit bytes) and output streams
(streams that write 8-bit bytes).
abstract
Super-classes
JSP
69
IO Stream Methods
(API)
InputStream defines the methods for reading bytes and arrays
of bytes:
int read()
int read(byte cbuf[])
int read(byte cbuf[], int offset, int length)
OutputStream defines the similar methods for bytes:
indicate a subrange
int write(int c)
in the target array
int write(byte cbuf[])
that needs to be filled.
int write(byte cbuf[], int offset, int length)
Others:
void close() ~ when you have finished with (I/O) streams
JSP
70
Related APIs in TCP/UDP S/C Programs
BufferedReader ~ Read text from a character-input stream,
•
buffering characters so as to provide for the efficient reading of
characters, arrays, and lines.
In general, each read request made of a Reader causes a
corresponding read request to be made of the underlying
character or byte stream. Advisable: to wrap a BufferedReader
around any Reader whose read() operations may be costly, such
as FileReaders and InputStreamReaders.
• Example:
BufferedReader in
= new BufferedReader(new FileReader(“foo.in”));
JSP
71
Related API (cont’d)
InputStreamReader
~ a bridge from byte streams to character streams. It reads bytes
and translates them into characters according to a specified
character encoding (specified by name or platform’s default)
• Example:
BufferedReader in
= new BufferedReader(new InputStreamReader(System.in)):
Wrapping an InputStreamReader within a BufferedReader
JSP
72
Related API (cont’d)
DataOutputStream
~ a data input stream lets an application write primitive Java
data types to an output stream in a portable way. An application
can then use a data input stream to read the data back in.
System (class fields listed below)
in ~ standard input stream (e.g., Keyboard or host/user
specified) – already open and ready to supply input data.
out ~ standard output stream (e.g., display output) – already
open and ready to accept output data. For example,
System.out.println(data);
err ~ standard error output stream (typical the display output)
JSP
73
Constructing and Initializing an Object
Constructor
~ a special method you can use to have more control over the
process. The instantiation process calls a constructor each time
you create an instance of a class – an object.
Example:
To build “duncan” as an instance of
the Cat class. Cat ( ) is the constructor
that is called or invoked by
Cat duncan = new Cat ( );
to ensure that you cannot have an
object with random values in it
JSP
Cat class may look like:
class Cat {{
String name;
// the constructor
public Cat ( ) {
name = “Duncan”;
}
}
Constructor conforms to all rules for regular methods except . . .
Constructor’s name is always the same as the classname
Constructors have no return type
74
Constructor (cont’d)
Overload a Constructor
to use the same name for several items in the same scope
Overlaod the constructor name by providing several constructors
with different argument lists. When you issue a new
Constructor(argument_list) call
JSP
Cat class may look like:
class Cat {{
String name;
// the constructor
public Cat( ) {
name = “Duncan”;
}
// another constructor
public Cat(String inName) {
name = inName;
}
}
• Two different ways to initiate Cat
class (the arguments list passed in the
new statement determines which
constructor is used):
Cat duncan = new Cat;
Cat kevin = new Cat(“Kevin”);
75
Multithreaded Programming
Process
an basic unit for allocating system resources (e.g., memory,
but (not including) CPU time)
a program in execution
Thread (or an execution context)
The process that get CPU time allocated
the encapsulation of a virtual CPU with its own program code
and data. A thread is composed of CPU, code, and data.
• Two threads share the same
code when they execute code
from instances of the same class.
JSP
• Two threads share the same
data when they share access to
a common object.
which the code works on
that CPU is executing
One or more threads constitute a process. And this process is
called multithread program (多執行緒程式).
76
Creating and Starting the Thread
• A Thread constructor takes an argument that is an instance of
Runnable. An instance of Runnable is made from a class that
implements the Runnable interface (that is, provide a public
void
run() method).
JSP
1 public class ThreadTest {
2 public static void main(String
args[]) {
constructs an instance
3 Xyz r = new Xyz();
4 Thread t = new Thread(r); r of class Xyz .
5 t.start();
Instance r has its own data,
in this case the integer i.
6 }
7 }
Calling start() places the virtual CPU embodied in the
thread into a runnable state becomes viable for
scheduling for execution by the JVM.
77
Creating and Starting the Thread
88
class
class Xyz
Xyz implements
implements Runnable
Runnable {{
99 int
int i;
i;
10
10
11
11 public
public void
void run()
run() {{
12
12 ii == 0;
0;
13
13 while
while (true)
(true) {{
14
System.out.println(“Hello
14
System.out.println(“Hello ”” ++ i++);
i++);
15
if
15
if (( ii ==
== 50
50 )) {{
16
break;
16
break;
17
17 }} }} }} }}
JSP
Multithreaded programming to create multiple threads based on
the same Runnable instance. Do this as follows:
Thread t1 = new Thread(r);
Thread t2 = new Thread(r);
In this case, both threads share the same data and code. Calling start()
method does necessarily not mean the thread runs immediately.
78
Possible Lifetime States of a Thread
JSP
79
To Be Continue . . .
JSP
80