Client/Server hai tầng (two-tier client/server) · 2013-03-22 · Ứng dng hai tầng cung cấp...

Preview:

Citation preview

� �

� Client/Server hai tầng (two-tier client/server)

� Client/Server ba tầng

� Kiến trúc n-tầng

� Ứng dụng hai tầng cung cấp nhiều trạm làm việc với một tầng trình diễn thống nhất, tầng này truyền tin với tầng lưu trữ dữ liệu tập trung. Tầng trình diễn thông Tầng trình diễn thông thường là client, và tầng lưu trữ dữ liệu là server.

� Hầu hết các ứng dụng Internet như là email, telnet, ftp thậm chí là cả Web là các ứng dụng hai tầng

� Một ứng dụng ñược chia thành 3 tầng tách biệt nhau về mặt logic. Tầng ñầu tiên là tầng trình diễn thường bao gồm các giao diện ñồ họa. Tầng thứ hai là tầng trung gian hay tầng tác nghiệp: Oracale, SQL Server, tài liệu XML... Tầng thứ ba chứa dữ liệu cần cho ứng Tầng thứ ba chứa dữ liệu cần cho ứng dụng. Tầng thứ ba về cơ bản là chương trình thực hiện các lời gọi hàm ñể tìm kiếm dữ liệu cần thiết. Tầng trình diễn nhận dữ liệu và ñịnh dạng nó ñể hiển thị. Sự tách biệt giữa chức năng xử lý với giao diện ñã tạo nên sự linh hoạt cho việc thiết kế ứng dụng. Nhiều giao diện người dùng ñược xây dựng và triển khai mà không làm thay ñổi logic ứng dụng.

Kiến trúc n-tầng ñược chia thành các tầng như sau:

� Tầng giao diện người dùng: quản lý tương tác của người dùng với ứng dụng

� Tầng logic trình diễn: Xác ñịnh cách thức hiển thị giao diện người dùng và các yêu cầu của người dùng ñược quản lý như người dùng và các yêu cầu của người dùng ñược quản lý như thế nào.

� Tầng logic tác nghiệp: Mô hình hóa các quy tắc tác nghiệp,

� Tầng các dịch vụ hạ tầng: Cung cấp một chức năng bổ trợ cần thiết cho ứng dụng như các thành phần (truyền thông ñiệp, hỗ trợ giao tác).

� A server (program) runs on a specific computer and has a socket that is bound to a specific port. The server waits and listens to the socket for a client to make a connection request.

serverClient

Connection request

port

� If everything goes well, the server accepts the connection.Upon acceptance, the server gets a new socket bounds to adifferent port. It needs a new socket (consequently adifferent port number) so that it can continue to listen to thedifferent port number) so that it can continue to listen to theoriginal socket for connection requests while serving theconnected client.

server

Client

Connectionport

port port

� Socket là một cuộc cách mạng của Berkeley UNIX, cho phép người lập trình xem một liên kết mạng như là 1 luồng mà có thể ñọc dữ liệu ra hay ghi dữ liệu vào từ luồng này.

� Về mặt lịch sử Socket là một sự mở rộng của một trong những ý tưởng quan trọng nhất một trong những ý tưởng quan trọng nhất của UNIX: tất cả các thao tác vào/ra giống như vào ra tệp tin ñối với người lập trình, cho dù ta ñang làm việc với bàn phím, màn hình ñồ họa, một file thông thường, hay một liên kết mạng. Các Socket che dấu người lập trình khỏi các chi tiết mức thấp của mạng như môi kiểu ñường truyền, các kích thước gói, yêu cầu truyền lại gói, các ñịa chỉ mạng...

� A socket is an endpoint of a two-way communication linkbetween two programs running on the network.

� A socket is bound to a port number so that the TCP layer canidentify the application that data destined to be sent.identify the application that data destined to be sent.

� Java’s .net package provides two classes:o Socket – for implementing a cliento ServerSocket – for implementing a server

ServerSocket(1234)Server

Socket(“128.250.25.158”, 1234)

Output/write stream

Input/read stream

It can be host_name like “mandroo.cs.mu.oz.au”

Client

1. Open the Server Socket:ServerSocket server; PrintWriter os;server = new ServerSocket(PORT);

2. Wait for the Client Request:Socket client = server.accept();

3. Create I/O streams for communicating to the client

os = new PrintWriter ( client.getOutputStream());BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));InputStreamReader(client.getInputStream()));

4. Perform communication with clientReceive from client: String line = in.readLine();

Send to client: os.println("Hello\n");

5. Close sockets: client.close();

For multithreaded server:

while(true) {i. wait for client requests (step 2 above)ii. create a thread with “client” socket as parameter (the

thread creates streams (as in step (3) and doescommunication as stated in (4). Remove thread onceservice is provided.

}

� accept( ) – accepts a connection request and creates a socket to the remote user

� close( ) – close the server socket and wait for next connection request

import java.net.*;

import java.io.*;

public class EchoServer1 {

public final static int DEFAULT_PORT=2007;

public static void main(String[] args) { int port=DEFAULT_PORT;

try { ServerSocket ss=new ServerSocket(port);

Socket s=null;

while(true) {while(true) {

try { s=ss.accept();

PrintWriter pw=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));

BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));

while(true){ String line=br.readLine();

if(line.equals("exit"))break;

String upper=line.toUpperCase();

pw.println(upper); pw.flush(); }

} catch(IOException e) { } finally{

try{ if(s!=null) { s.close();} } catch(IOException e){}

}

}

} catch(IOException e) { }

}

� A new ServerSocket is created on a particular port using a ServerSocket( ) constructor.

� The ServerSocket listens for incoming connection attempts on that port using its accept( ) method. accept( ) blocks until a client attempts to make a connection, at which point a client attempts to make a connection, at which point accept( ) returns a Socket object connecting the client and the server.

� Depending on the type of server, either the Socket'sgetInputStream( ) method, getOutputStream( ) method, orboth are called to get input and output streams thatcommunicate with the client.

� The server and the client interact according to an agreed-uponprotocol until it is time to close the connection.

� The server, the client, or both close the connection.� The server, the client, or both close the connection.

� The server returns to step 2 and waits for the next connection.

ServerSocket server = new ServerSocket(8888);Socket client = server.accept();

PrintWriter pw = new PrintWriter(client.getOutputStream());BufferedReader br = new BufferedReader(new InputStreamReader

(client.getInputStream()));String st;boolean ketthuc = false;do{do{

st=br.readLine();if (st.equalsIgnoreCase("bye")) {

ketthuc=true;}

Scanner scn = new Scanner(System.in);pw.write(scn.nextLine());

pw.flush(); } while (!ketthuc);

1. Create a Socket Object:

client = new Socket(server, port_id);

2. Create I/O streams for communicating with the server.

is = new PrintWriter (client.getInputStream());

BufferedReader os = new BufferedReader(new BufferedReader os = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()))

3. Perform I/O or communication with the server:o Receive data from the server:

String line = is.readLine(); o Send data to the server:

os.println("Hello\n");

4. Close the socket when done:

client.close();

Socket server = new Socket(IPServer, 8888);PrintWriter pw = new PrintWriter (server.getOutputStream(), true);BufferedReader br = new BufferedReader (new InputStreamReader

(server.getInputStream()));String st;boolean ketthuc = false; do {

//Gui thong tinScanner scn = new Scanner(System.in);Scanner scn = new Scanner(System.in);pw.write(scn.nextLine());pw.write("\n");pw.flush(); //Nhan thong tin

st=br.readLine();System.out.println(st);if (st.equalsIgnoreCase("bye")) { ketthuc=true; }

} while (!ketthuc);

public class EchoServer { public static void main(String[] args) throws IOException {

ServerSocket serverSocket = null;

serverSocket = new ServerSocket(10007); serverSocket = new ServerSocket(10007); Socket clientSocket = null; clientSocket = serverSocket.accept();

PrintWriter out = new PrintWriter(clientSocket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

String inputLine; while ((inputLine = in.readLine()) != null) {

System.out.println ("Server: " + inputLine); System.out.println ("Server: " + inputLine); out.println(inputLine); if (inputLine.equals("Bye."))

break; }

out.close(); in.close(); clientSocket.close(); serverSocket.close();

} }

public class EchoClient {public static void main(String[] args) throws IOException {

String serverHostname = new String ("127.0.0.1");Socket echoSocket = null;Socket echoSocket = null;PrintWriter out = null;BufferedReader in = null;

echoSocket = new Socket(serverHostname, 10007);//out put result to serverout = new PrintWriter(echoSocket.getOutputStream(), true);

//get input from the Serverin = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));

BufferedReader stdIn = new BufferedReader( new InputStreamReader(System.in));String userInput;

System.out.print ("input: ");while ((userInput = stdIn.readLine()) != null) {

out.println(userInput);System.out.println("echo: " + in.readLine());

System.out.print ("input: ");}

out.close();in.close();stdIn.close();echoSocket.close();

}}

import java.net.*;

import java.io.*;

class PortScanner

{

public static void main(String[] args) {

String host="localhost";

if(args.length>0){ host=args[0]; }if(args.length>0){ host=args[0]; }

for(int i=0;i<1024;i++){

try{

Socket s=new Socket(host,i);

System.out.println("Co mot server dang hoat dong tren cong:"+i);

} catch(UnknownHostException e){ System.err.println(e); }

catch(IOException e) { System.err.println(e); }

}

}

}

import java.net.*;

import java.io.*;

public class EchoClient1

{

public static void main(String[] args) {

String hostname="localhost";

if(args.length>0) {if(args.length>0) {

hostname=args[0];

}

PrintWriter pw=null;

BufferedReader br=null;

try{

Socket s=new Socket(hostname,2007);

br=new BufferedReader(new InputStreamReader(s.getInputStream()));

BufferedReader user=new BufferedReader(new InputStreamReader(System.in));

pw=new PrintWriter(s.getOutputStream());

System.out.println("Da ket noi duoc voi server...");

while(true) {

String st=user.readLine();

if(st.equals("exit")) { break; }

pw.println(st);

pw.flush();pw.flush();

System.out.println(br.readLine());

}

} catch(IOException e) { System.err.println(e); }

finally { try {

if(br!=null)br.close();

if(pw!=null)pw.close();

} catch(IOException e) {

System.err.println(e); }

}

}

}

� The User Datagram Protocol (UDP) is an alternativeprotocol for sending data over IP

� UDP is very quick, but not reliable.� Java's implementation of UDP is split into two classes: � Java's implementation of UDP is split into two classes:

DatagramPacket and DatagramSocket.� The DatagramPacket class stuffs bytes of data into UDP

packets called datagrams and lets you unstuff datagrams thatyou receive.

� A DatagramSocket sends as well as receives UDPdatagrams.

1) Write a EchoUDP server which will send back any message received from client.

2) Write a UDPclient which sends some message to the EchoUDP server for testing it.for testing it.

� Java introduce the new I/O (NIO) API in v1.4.� New features:a) Buffers for data of primitive typesb) Character-set encoders and decodersb) Character-set encoders and decodersc) A pattern-matching facility based on Perl-style regular expressions

d) Channels, a new primitive I/O abstractione) A file interface that supports locks and memory mappingf)A multiplexed, non-blocking I/O facility for writing scalable

servers

� Allow Java programmers to implement high-speed I/O.

� NIO deals with data in blocks which can be much faster thanprocessing data by the (streamed) byte.

� Hệ thống vào ra mớI ñược xây dựng dựa trên hai hạng mục cơbản là: buffer và channel. Một vùng ñệm (buffer) lưu trữ dữbản là: buffer và channel. Một vùng ñệm (buffer) lưu trữ dữliệu. Một kênh (channel) biểu diễn một liên kết mở tới mộtthiết bị vào ra mới, như tệp tin hoặc một socket. ðể sử dụng hệthống vào ra mới, ta phải nhận một kênh truyền tới một thiết bịvào ra và một vùng ñệm ñể lưu trữ dữ liệu. Sau ñó ta có thểthực hiện thao tác trên vùng ñệm ñể vào và ra dữ liệu.

1) Buffers

2) Channels

3) Selectors

4) Regular Expressions

5) Character Set Coding5) Character Set Coding

� In the NIO library, all data is handled with buffers.� A buffer is essentially an array. Generally, it is an array of bytes, but

other kinds of arrays can be used.� A buffer also provides structured access to data and also keeps track

of the system's read/write processes.of the system's read/write processes.Types:a) ByteBuffer b) CharBuffer c) ShortBuffer d) IntBuffere) LongBuffer·f) FloatBufferg) DoubleBuffer

� Channel is like a stream in original I/O.

� You can read a buffer from and write a buffer to a channel. Unlike streams, channels are bi-directional.

� Các kênh ñược ñịnh nghĩa trong gói java.io.channel. Một kênh biểu diễn một liên kết mở tới một nguồn hoặc ñích vào ra. Ta có thể nhận ñược một kênh bằng cách gọi phương thức getChannel() trên một ñối tượng hỗ trợ kênh. Java 2 phiên bản 1.4 ñưa thêm vào phương thức getChannel() cho các lớp sau:

� FileInputStream

� FileOutputStream

� RandomAccessFile

� Socket� Socket

� ServerSocket

� DatagramSocket

� ðể nhận ñược một kênh, trước tiên phải nhận một ñối tượng của các lớp này và sau ñó gọi phương thức getChannel() trên ñối tượng ñó.

� Kiểu kênh cụ thể ñược trả về phụ thuộc vào kiểu ñối tượng chịu tác ñộng của phương thưc getChannel(). Ví dụ khi gọi phương thức getChannel() trên ñối tượng FileInputStream, FileOutputStream hoặc RandomFileAccess thì kênh trả về là FileChannel. Khi gọi phương thức getChannel() trên ñối tượng Socket thì kiểu kênh trả về là SocketChannel().

� Các kênh FileChannel và SocketChannel hỗ trợ các phương thức read() và write() cho phép ta thực hiện các thao tác vào ra thông qua kênh

Codes for reading from a file:

FileInputStream fin =new

FileInputStream( "readandshow.txt");

FileChannel fc = fin.getChannel();

ByteBuffer buffer = ByteBuffer.allocate(1024);

f c.read(buffer);

import java.io.*;import java.nio.channels.FileChannel;import java.nio.ByteBuffer;public class copyFileExample {public static void main(String []args) throws Exception{{

String source ="D:\\java_examples\\hello.txt";String des = "D:\\java_examples\\hello2.txt";FileInputStream fis = new FileInputStream(source);FileOutputStream fos = new FileOutputStream(des);//Get the FileChannel of FileInputStream instanceFileChannel fci = fis.getChannel();FileChannel fco = fos.getChannel();

ByteBuffer buffer = ByteBuffer.allocate(1024);while(true) {

int read = fci.read(buffer);if(read == -1)

break;// flip the buffer// flip the bufferbuffer.flip();//write to the destination channelfco.write(buffer);

// clear the buffer and user it for the next read processbuffer.clear();

}} }

Refer to the example, please use the NIO to create a programto write a String to a text file and store in your computer.

� Channels and buffers are really intended for server systemsthat need to process many simultaneous connectionsefficiently.

� Handling servers requires the new selectors that allow theserver to find all the connections that are ready to receiveserver to find all the connections that are ready to receiveoutput or send input.

� Asynchronous I/O is made possible in NIO with scalable sockets, which consist of the following components:

a) Selectable Channel - A channel that can be multiplexed b)Selector - A multiplexor of selectable channelb)Selector - A multiplexor of selectable channelc)Selection key - A token representing the registration of a selectable

channel with a selector

1) Create a Selector and register channels with ito Use Open() method to create a Selector.

o The register() method is on SelectableChannel, not Selector

2) Invoke select() method on the Selector object2) Invoke select() method on the Selector object

3) Retrieve the Selected Set of keys from the Selectoro Selected set: Registered keys with non-empty Ready Sets

o Keys = selector.selectedKeys()

4) Iterate over the Selected Seta) Check each key's Ready Setb) Remove the key from the Selected Set (iterator.remove())

* Bits in the Ready Sets are never reset while the key is in the * Bits in the Ready Sets are never reset while the key is in the Selected Set* The Selector never removes keys from the Selected Set —you must do soc) Service the channel (key.channel()) as appropriate (read, write, etc)

Skeleton does for a simple server with NIO:

//Open a ServerSocketChannelServerSocketChannel serverChannel = ServerSocketChannel.open ( );ServerSocketChannel serverChannel = ServerSocketChannel.open ( );

//make the ServerSocketChannel non-blocking.//necessary for asynchronous i/o

serverChannel.configureBlocking(false);

ServerSocket ss = serverChannel.socket( );

// bind the socket to aspecific port

ss.bind(new InetSocketAddress(PORT_NO));

//Open the selectorSelector selector = Selector.open( );

//use the channel's register() method to register the//ServerSocketchannel with the selector.serverChannel.register(selector, SelectionKey.OP_ACCEPT);

/*check whether anything is ready to be acted on, call the selector'sselect() method. For a long-running server,this normally goes in an infinite loop:

*/while (true) {while (true) {

try {selector.select( );

}catch (IOException ex)

{ ex.printStackTrace( ); break;}}

� Starting from JDK 1.4, Java Secure Sockets Extension(JSSE) is part of the standard distribution.

� JSSE uses the Secure Sockets Layer (SSL) Version 3 and� JSSE uses the Secure Sockets Layer (SSL) Version 3 andTransport Layer Security (TLS) protocols and theirassociated algorithms to secure network communications.

� JSSE abstracts all the low-level details such as keysexchange, authentication, and data encryption. All you haveto do is to send your data over the streams from the securedsockets obtained..

The Java Secure Socket Extension is divided into four packages:1) javax.net.ssl : The abstract classes that define Java's API for secure

network communication.2) javax.net: The abstract socket factory classes used instead of2) javax.net: The abstract socket factory classes used instead of

constructors to create secure sockets.3) javax.security.cert: A minimal set of classes for handling public key

certificates that's needed for SSL in Java 1.1. (In Java 1.2 and later, thejava.security.cert package should be used instead.)

4) com.sun.net.ssl: The concrete classes that implement the encryptionalgorithms and protocols in Sun's reference implementation of theJSSE.

� http://www.herongyang.com/JDK/

� E-mail is sent by socket communication with port 25 on acomputer system.

� open a socket connected to port 25 on some system, and speak“mail protocol” to the daemon at the other end.“mail protocol” to the daemon at the other end.

import java.io.*;

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

URL yahoo = new URL("http://www.yahoo.com/"); URL yahoo = new URL("http://www.yahoo.com/");

URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader(new

InputStreamReader(yc.getInputStream()));

String inputLine

while ((inputLine = in.readLine()) != null) System.out.println(inputLine);

in.close(); }

}

import java.io.*; import java.net.*;public class URLConnectionReader { public static void main(String[] args) throws Exception {

URL yahoo = new URL("http://www.yahoo.com/"); URL yahoo = new URL("http://www.yahoo.com/");

URLConnection yc = yahoo.openConnection(); BufferedReader in = new BufferedReader(new

InputStreamReader(yc.getInputStream()));

String inputLine ;

while ((inputLine = in.readLine()) != null) System.out.println(inputLine);

in.close(); }

}

Recommended