Professional Documents
Culture Documents
GIO TRNH
IT
LP TRNH MNG
PT
H MNH O
H NI, 07/2010
M U
Ngy nay do nhu cu thc t v do s pht trin mnh m ca nhiu cng ngh tch hp,
dn n cc chng trnh ng dng hin ny hu ht u c kh nng thc hin trn mi
trng mng my tnh ni ring v mng tch hp ni chung. Chnh v vy gio trnh ny
nhm cung cp cho sinh vin nhng kin thc v k thut c bn nht pht trin cc
chng trnh ng dng mng. Gio trnh ny bao gm 4 phn ln v 7 chng: Phn th
nht trnh by cc kin thc c s cho lp trnh mng, ch yu l kin thc mng my
tnh, ngn ng lp trnh v m hnh lp trnh mng. Phn 2 v 3 cung cp cho sinh vin 2
IT
PT
MC LC
PT
IT
1
1
1
1
2
2
2
4
5
6
6
6
6
6
6
7
7
8
8
10
10
10
10
10
10
15
17
17
17
17
19
20
20
20
22
4. Mt s chng trnh v d
4.1. Chng trnh qut cng s dng Socket
4.2. Chng trnh qut cng cc b dng lp ServerSocket
4.3. Chng trnh finger client
4.4. Chng trnh cho php ly thi gian server v client
IV. LP TRNH NG DNG MNG VI UDPSOCKET
1. Giao thc UDP v c ch truyn thng UDP
2. Mt s lp Java h tr lp trnh vi UDPSocket
2.1. Lp DatagramPacket
2.2. Lp DatagramSocket
3. K thut lp trnh truyn thng vi giao thc UDP
3.1. Pha server
PT
IT
23
23
24
24
25
28
28
28
28
30
33
33
33
33
34
35
35
35
38
41
43
43
45
47
48
48
48
49
49
49
50
53
57
58
58
58
58
60
PT
IT
63
68
68
68
73
76
76
84
87
88
88
88
88
88
91
92
92
95
95
96
97
97
97
99
102
102
103
107
98
98
101
102
102
108
108
108
108
110
111
113
118
118
118
118
118
119
120
122
130
131
131
131
131
131
132
134
135
136
136
137
141
142
PT
IT
PT
IT
Vn lp trnh mng lin quan nhiu lnh vc kin thc khc nhau. T kin thc s dng
ngn ng lp trnh, phn tch thit k h thng, kin thc h thng mng, m hnh xy dng
chng trnh ng dng mng, kin thc v c s d liu... cho n kin thc truyn thng,
cc kin thc cc lnh vc lin quan khc nh mng in thoi di ng, PSTN, h thng
GPS, cc mng nh BlueTooth, WUSB, mng sensor.... Nhng c th ni vn lp trnh
mng c 3 vn chnh ct li tch hp trong lp trnh ng dng mng v c th hin nh
hnh 1.
Trong giao trnh ny, chng ti tp trung ch yu vo cc k thut pht trin chng trnh ng
dng mng. Cn cc vn khc can thip su xung pha thp hn trong h thng mng nh cc
trnh tin ch mng, thu thp bt v phn tch gi tin...cc bn c th tham kho cc ti liu khc,
nht l cc ti liu lin quan n lp trnh vi Raw socket.
II. MT S KIN THC MNG C S LP TRNH MNG
PT
IT
Qu trnh truyn thng ch c mt giai on duy nht l truyn d liu, khng c giai
on thit lp kt ni cng nh hu b kt ni.
D liu truyn c t chc thnh cc tin gi tin c lp, trong mi gi d liu c cha
a ch ni nhn.
IT
Giao thc dch v: Telnet, FTP, TFTP, SMTP, POP3, IMAP4, DNS, HTTP...
PT
Hai phin bn a ch IP thng dng: IPv4 v IPv6. Hin th gii cng nh Vit Nam ang
chuyn dn sang s dng IPv6.
1.3.2. Mt n(mask)
-> 10.255.255.255
PT
IT
a s cc h iu hnh mng hin nay u a nhim nn cho php nhiu tin trnh truyn thng
chy ng thi trn cng mt my tnh v u chung mt a ch IP. Chnh v nh vy, 2 tin
trnh trn 2 my tnh mun truyn thng vi nhau m ch s dng a ch IP l cha th thc hin
c. phn bit cc tin trnh chy trn cng mt my tnh ng thi, ngi ta gn cho mi
tin trnh mt nhn duy nht phn bit cc tin trnh vi nhau. Trong k thut mng my tnh,
ngi ta s dng mt s nguyn 16 bt lm nhn v n c gi l s hiu cng hoc a ch
cng(port). a ch cng ny c s dng v c qun l bi tng giao vn v n c gi tr t 0
n 65535, c chia lm 3 gii:
M t
Echo
Discard
13
Daytime
19
Chargen
20
FTP,Data
21
FTP,Control
23
Telnet
Mng u cui
25
SMTP
53
DNS
67
BOOTP
79
Finger
Finger
80
HTTP
111
RPC
Giao thc gi th tc t xa
110
POP3
143
IMAP4
IT
port
Tr v ngy v gi
Tr v mt chui k t
PT
IT
PT
ICMP
Stream socket: cho php truyn thng vi cc giao thc truyn thng hng kt ni m
tiu biu l giao thc TCP(TCPSocket). TCP s dng mt cp stream socket kt ni
mt chng trnh ng dng vi mt chng trnh ng dng khc qua mng Internet.
Datagram socket: Cho php truyn thng vi cc giao thc hng khng kt ni, tiu biu
l giao thc UDP (UDP socket). UDP s dng mt cp datagram socket gi thng ip
t mt chng trnh ng dng ti mt chng trnh ng dng khc qua mng Internet.
Raw socket: y l kiu giao socket cho php truyn thng n cc giao thc tng
mng thp hn c tng giao vnm tiu biu nht l giao thc ICMP ca tng Internet
hoc OSPF. V d chng trnh ping s dng kiu socket ny.
II. CC M HNH LP TRNH MNG
1. M hnh client/server
Chng trnh ng dng mng t chc theo m hnh client/server c s dng ph bin trong
thc t. Chng trnh ng dng mng theo m hnh ny gm c 2 phn mm: Phn mm
Server
Client_1
Client_2
Client_n
PT
IT
Chng trnh ng dng mng lm vic theo m hnh peer-to-peer(ngang cp, bnh ng) c th
ni l cc chng trnh m c th thc hin vai tr ca c server v ca client. Chng trnh ny
khi chy c th yu cu chng trnh khc phc v n v n cng c th phc v yu cu gi ti
t chng trnh khc.
3. M hnh a tng
M hnh a tng gm nhiu tng m tiu biu nht l m hnh 3 tng. Trong m hnh ny, tng
thp nht l tng thng tin, tng trung gian v tng nh. Mt v d tiu biu ca m hnh 3 tng
l dch v Web vi tng nh l trnh duyt, tng trung gian l webserver v tng thng tin l
c s d liu. M hnh nhiu tng s c kho st k trong phn lp trnh ng dng mng nng
cao vi cc k thut Servlet, EJB, Portlet..
III . NGN NG LP TRNH MNG
1. Gii thiu chung
C/C++
Java
.NET
ASP
IT
i vi pht trin ng dng mng hin nay c 2 ngn ng lp trnh c s dng ph bin nht,
l .NET v JAVA. Ngi lp trnh c th s dng thnh tho mt trong 2 dng ngn ng
pht trin ng dng mng( vi Vit Nam ni chung nn nm tt c 2 cng ngh ny). Trong
gio trnh ny chng ti s s dng ngn ng lp trnh JAVA v cc cng ngh lin quan n n
pht trin ng dng mng. Sau khi nm chc k thut, t tng lp trnh mng thng qua ngn
ng Java, sinh vin c th s dng bt k ngn ng lp trnh no ph hp nh VB.NET, C#, ...
2. Lp trnh mng bng ngn ng Java
PT
lp trnh mng bng ngn ng Java, sinh vin phi nm chc mt s kin thc lp trnh java
sau:
Lp trnh Java c s
Lp trnh kt ni vi c s d liu
Ngoi l v x l ngoi l
Ngoi ra sinh vin cn phi hiu v my o java dnh cho cc ng dng java khc nhau(JVM,
KVM, my o cho dng SPOT...).
IV. K THUT LP TRNH MNG
C nhiu k thut lp trnh mng khc nhau, nhng trong gio trnh ny ch yu ch tp trung vo
3 k thut lp trnh mng chnh:
-
K thut lp trnh mng vi socket: Trong k thut ny, chng trnh ng dng
mng s c xy dng vi cc kiu socket khc nhau. K thut ny cho php mi
quan h qua mng gia cc chng trnh chy lng lo v bn thn socket l giao
din mng , khng phi c ch truyn thng.
-
K thut lp trnh phn tn: Tri vi k thut lp trnh socket, trong k thut ny
mi quan h gia chng trnh client v server l gn kt cht ch. K thut lp
trnh ny thc cht l k thut lp trnh phn tn m lnh(i tng), cho php
phn ti tnh ton ln cc my tnh kt ni vi nhau vi quan h hu c thay v tp
trung trn cng mt my. iu ny cho php tn dng ti nguyn mng gii
quyt cc bi ton vi khi lng tnh ton ln, thi gian thc.
K thut lp trnh truyn thng qua mng in thoi cng cng PSTN.
PT
IT
Thnh phn View (V): trnh din, hay cn c gi vi cc tn khc nh giao din
(interface), bin (boundary). C nhim v hin th cc form nhp d liu v hin th
kt qu x l t h thng cho ngi dng.
Khi ngi dng click vo nt Login, h thng phi kim tra trong c s d liu xem
c username/password y khng. Nu c th thng bo thnh cng, nu sai th thng
bo username/password khng hp l.
PT
IT
Hnh 1. 7: S lp ca h thng
S lp ca h thng c thit k theo m hnh MVC trong Hnh 1.7, bao gm 3 lp chnh
tng ng vi s M-V-C nh sau:
-
Lp LoginModel: l lp tng ng vi thnh phn model (M), bao gm hai thuc tnh
username v password, cc hm khi to v cc cp getter/setter tng ng vi cc
thuc tnh.
Tun t cc bc x l nh sau:
PT
public LoginModel(){
}
IT
package login_GUI_MVC;
Lp LoginView.java
package login_GUI_MVC;
import java.awt.FlowLayout;
import
import
import
import
import
import
import
import
import
import
import
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JOptionPane;
javax.swing.JPanel;
javax.swing.JPasswordField;
javax.swing.JTextField;
IT
PT
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
}
public LoginModel getUser(){
model = new LoginModel(txtUsername.getText(), txtPassword.getText());
return model;
}
public void showMessage(String msg){
JOptionPane.showMessageDialog(this, msg);
}
Lp LoginControl.java
package login_GUI_MVC;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
IT
view.addLoginListener(new LoginListener());
}
PT
if (rs.next()) {
return true;
}
con.close();
}catch(Exception e) {
throw e;
}
return false;
}
}
Lp Test.java
IT
package login_GUI_MVC;
public class Test {
public static void main(String[] args) {
LoginView view
= new LoginView();
LoginControl controller = new LoginControl(view);
view.setVisible(true);
}
}
PT
Kt qu
Login li:
VI. KT LUN
PT
IT
Trong chng ny chng ta im qua mt s kin thc c s cho lp trnh mng bao gm kin
thc mng truyn thng, m hnh lp trnh mng v ngn ng lp trnh mng. V thng qua
chng ny sinh vin cng nm c mc ch ca mn lp trnh mng. Cc chng tip theo s
lm r cc k thut lp trnh mng c bn v ch ra lp trnh mng an ton bo mt. Cn nhng
k thut lp trnh mng phc tp khc nh CORBA, EJB, PORTAL, JAVAMAIL hoc cng
ngh m my(cloud) cng nh m hnh a tng, k thut lp trnh hng dch v SOA s c
xt trong gio trnh lp trnh mng nng cao. Cn k thut lp trnh cc dch v mng di ng
nh SMS, MMS, cc dch v mng di ng khc v mng Bluetooth, mng Sensor, ZeeBig,
WUSB, GPS...sinh vin s c cung cp qua mn lp trnh thit b di ng, qua cc bi tp thc
hnh v h thng bi tp ln ca mn lp trnh mng.
PT
IT
byte[]
getAddress()
Tr v a ch IP cha trong i tng InetAddress dng mng byte
IT
boolean
PT
static InetAddress
static InetAddress
static InetAddress
getByName(String host)
Xc nh a ch IP ca my trm t tn ca my trm(host)
String
getCanonicalHostName()
Ly tn min ca a ch IP
String
getHostAddress()
Tr v a ch IP cha trong i tng INetAddress l chui dng a.b.c.d
String
getHostName()
Tr v tn my trm cha trong i tng
static InetAddress
getLocalHost()
Ly i tng InetAddress ca my cc b
int
hashCode()
Tr v hashcode ca a ch IP cc th
isAnyLocalAddress()
Kim tra a ch InetAddress c phi a ch wildcard khng?
boolean
isLinkLocalAddress()
Kim tra a ch c phi l mt a ch link-local hay khng.
boolean
isLoopbackAddress()
Kim tra a ch c phi l a ch Loopback khng.
boolean
isMCGlobal()
Kim tra a ch multicast c phm vi ton cc hay khng?
boolean
isMCLinkLocal()
Kim tra a ch multicast c phi l a ch c phm vi lin kt hay
khng?
boolean
isMCNodeLocal()
Kim tra a ch multicast c phi l a ch phm vi nt mng hay
khng?
boolean
isMulticastAddress()
Kim tra a ch InetAddress c phi l a ch IP multicast hay
khng.
PT
String
IT
boolean
toString()
Chuyn a ch IP thnh chui.
System.out.println(address);
}
catch (UnknownHostException ex) {
System.out.println("Could not find www.yahoo.com");
}
//AllAddr.java
import java.net.*;
public class AllAddr{
IT
PT
try {
InetAddress[] addresses =
InetAddress.getAllByName("www.microsoft.com");
}
}
www.microsoft.com/63.211.66.116
www.microsoft.com/63.211.66.107
www.microsoft.com/63.211.66.118
www.microsoft.com/63.211.66.115
www.microsoft.com/63.211.66.110
IT
PT
try {
InetAddress ia = InetAddress.getByName("208.201.239.37");
System.out.println(ia.getHostName( ));
System.err.println(ex);
}
catch (UnknownHostException ex) {
System.out.println("I'm sorry. I don't know my own address.");
}
}
}
IT
PT
System.out.println((address[i]>0)?address[i]: (address[i]+256));
IT
if (address.isAnyLocalAddress( )) {
System.out.println(address + " is a wildcard address.");
}
if (address.isLoopbackAddress( )) {
PT
if (address.isLinkLocalAddress( )) {
System.out.println(address + " is a link-local address.");
}
else if (address.isSiteLocalAddress( )) {
System.out.println(address + " is a site-local address.");
}
else {
address.");
}
else if (address.isMCLinkLocal( )) {
System.out.println(address + " is a subnet wide multicast
address.");
}
else if (address.isMCNodeLocal( )) {
System.out.println(address
+ " is an interface-local multicast address.");
}
else {
System.out.println(address + " is an unknown multicast
address type.");
}
}
else {
IT
PT
Sau khi bin dch chng trnh, chy chng trnh vi lnh:
java IPCharacteristics
<addresss> [Enter]
Cu t ny cho php to ra i tng Socket truyn thng vi giao thc TCP v thc hin kt
ni vi my trm t xa c a ch v s cng c ch ra bi tham s host v port tng ng.
Tham s host c th l tn my trm, tn min hoc a ch IP. Nu khng tm thy my trm t
IT
PT
SO_BINDADDR
SO_TIMEOUT
SO_LINGER
IT
PT
Lp ServerSocket cho php to i tng socket pha server v truyn thng vi giao thc TCP.
Sau khi c to ra, n c t trng thi lng nghe( trng thi th ng) ch tn hiu kt ni
gi ti t client.
2.2.1 Cc cu t
ss.bind(http);
while (true) {
IT
PT
Trong chng trnh ng dng mng xy dng theo m hnh client/server, chng trnh client
v chng trnh server c th truyn thng c vi nhau th mi pha phi thc hin ti thiu
cc thao tc c bn sau y(Hnh 2.2 ):
IT
PT
Khai bo lng nhp/xut cho Socket. Lung nhp/xut c th l lung kiu byte
hoc kiu char.
Thc hin truyn d liu qua mng thng qua lung nhp/xut
Lu :
Bnh thng chng trnh server lun chy trc chng trnh client
V d:
import java.io.*;
import java.net.*;
public class EchoClient {
public static void main(String[] args) throws IOException {
IT
} catch (UnknownHostException e) {
} catch (IOException e) {
PT
System.exit(1);
String userInput;
IT
OutputStream outp=cl.getOutputStream();
PT
+ Vit d liu:
b;
- Vi lung nhp:
InputStreamReader(cl.getInputStream()));
String s=inp.readLine();
- Vi lung xut:
+ To lung xut:
PrintWriter outp=new PrintWriter(cl.getOutputStream(),true);
+ Vit d liu:
outp.println(<data>);
4. Mt s v d
4.1. Chng trnh qut cng s dng Socket
//PortScanner.java
import java.net.*;
import java.io.*;
public class PortScanner {
public static void main(String[] args) {
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
try {
InetAddress theAddress = InetAddress.getByName(host);
for (int i = 1; i < 65536; i++) {
try {
IT
PT
finally {
try {
// end main
// end PortScanner
import java.io.*;
public class LocalPortScanner {
public static void main(String[] args) {
for (int port = 1; port <= 65535; port++) {
try {
// the next line will fail and drop into the catch block if
// there is already a server running on the port
ServerSocket server = new ServerSocket(port);
}
catch (IOException ex) {
System.out.println("There is a server on port " + port + ".");
} // end catch
} // end for
}
IT
Finger l mt giao thc truyn thng theo RFC 1288, client to kt ni TCP ti server vi s
cng 79 v gi mt truy vn on-line ti server. Server p ng truy vn v ng kt ni.
import java.net.*;
PT
import java.io.*;
public class FingerClient {
hostname = args[0];
}
IT
PT
import java.net.*;
import java.io.*;
import java.util.*;
DEFAULT_PORT = 37;
IT
PT
// end try
System.err.println(ex);
}
finally {
try {
if (raw != null) raw.close( );
}
catch (IOException ex) {}
}
}
// end main
} // end TimeClient
//TimeServe.java
import java.net.*;
import java.io.*;
import java.util.Date;
public class TimeServer {
public final static int DEFAULT_PORT = 37;
IT
port = Integer.parseInt(args[0]);
PT
}
}
// end while
// end try
PT
} // end main
IT
} // end TimeServer
Chng trnh pha client TCP phi hin giao din ha, trong c mt text
nhp username, mt text nhp password, v mt nt nhn Login.
Ti pha server, mi khi nhn c thng tin ng nhp gi t client, n s tin hnh
kim tra trong c s d liu xem c ti khon no trng vi thng tin ng nhp nhn
c hay khng.
Sau khi c kt qu kim tra (ng nhp ng, hoc sai), server TCP s gi kt qu ny
v cho client tng ng, theo ng giao thc TCP.
pha client, sau khi nhn c kt qu ng nhp (ng nhp ng, hoc sai) t
server, n s hin th thng bo tng ng vi kt qu nhn c: nu ng nhp
PT
IT
S lp ca pha client c thit k theo m hnh MVC trong Hnh 2.3, bao gm 3 lp chnh
tng ng vi s M-V-C nh sau:
-
Lp User: l lp tng ng vi thnh phn model (M), bao gm hai thuc tnh
username v password, cc hm khi to v cc cp getter/setter tng ng vi cc
thuc tnh.
PT
IT
IT
PT
3. Lp ClientControl gi thng tin cha trong i tng User ny sang pha server
kim tra ng nhp
4. Bn pha server, khi nhn c thng tin ng nhp trong i tng User, n s
gi phng thc checkLogin() km tra thng tin ng nhp trong c s d liu.
5. Kt qu kim tra s c tr v cho lp ClientControl
6. pha client, khi nhn c kt qu kim tra ng nhp, lp ClientControl s
chuyn cho lp LoginView hin th bng phng thc showMessage()
7. Lp LoginView hin th kt qu ng nhp ln cho ngi dng
5.3 Ci t
5.3.1 Cc lp pha client
User.java
package tcp.client;
import java.io.Serializable;
public class User implements Serializable{
private String userName;
private String password;
public User(){
}
ClientView.java
IT
PT
package tcp.client;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
content.add(btnLogin);
this.setContentPane(content);
this.pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
}
public User getUser(){
User model = new User(txtUsername.getText(), txtPassword.getText());
return model;
}
IT
PT
ClientControl.java
package tcp.client;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
ObjectInputStream ois =
new ObjectInputStream(mySocket.getInputStream());
Object o = ois.readObject();
if(o instanceof String){
String result = (String)o;
if(result.equals("ok"))
view.showMessage("Login succesfully!");
else view.showMessage("Invalid username and/or password!");
}
mySocket.close();
} catch (Exception ex) {
view.showMessage(ex.getStackTrace().toString());
}
}
}
}
ClientRun.java
package tcp.client;
PT
IT
package tcp.server;
ServerControl.java
package tcp.server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import tcp.client.User;
public class ServerControl {
private ServerView view;
private Connection con;
private ServerSocket myServer;
private Socket clientSocket;
private int serverPort = 8888;
public ServerControl(ServerView view){
this.view = view;
getDBConnection("usermanagement", "root", "12345678");
openServer(serverPort);
view.showMessage("TCP server is running...");
while(true){
listenning();
}
}
IT
PT
try {
Class.forName(dbClass);
con = DriverManager.getConnection (dbUrl, username, password);
}catch(Exception e) {
view.showMessage(e.getStackTrace().toString());
}
}
}catch (Exception e) {
view.showMessage(e.toString());
}
}
ServerRun.java
package tcp.server;
IT
5.5 Kt qu
PT
Login li:
IT
Lp ny cho php to gi tin truyn thng vi giao thc UDP. Lp ny kt tha trc tip t lp
Object.
public final class DatagramPacket extends Object
Gi tin l i tng ca lp ny cha 4 thnh phn quan trng: a ch, d liu truyn tht s,
kch thc ca gi tin v s hiu cng cha trong gi tin.
2.1.1. Cu t
PT
Tham s:
V d to gi tin nhn:
byte[] inBuff=new byte[512];//b m nhp
DatagramPacket inData=new DatagramPacket(inBuf, inBuff.length);
* Cu t to gi tinh gi:
public DatagramPacket(byte[] outBuffer , int length,
InetAddress destination, int port)
Tham s:
length: kch c d liu ca gi tin gi tnh theo s byte v thng bng outBuffer.length.
V d:
String s= Hello World!;
//B m xut v gn d liu cho b m xut
byte[] outBuff=s.getBytes();
//a ch ch
InetAddress addrDest=InetAddress.getByName(localhost);
//S cng ch
int
portDest=3456;
//To gi tin gi
DatagramPacket outData=new DatagramPacket(outBuff,
outBuff.length, addrDest, portDest);
public byte[] getData( ): Tr v d liu cha trong gi tin di dng mng byte.
public int getLength( ): Tr v kch c ca d liu cha trong gi tin tnh theo s byte.
IT
PT
Lp DatagramSocket cho php to ra i tng socket truyn thng vi giao thc UDP. Socket
ny cho php gi/nhn gi tin DatagramPacket. Lp ny c khai bo k tha t lp Object.
public class DatagramSocket extends Object
// send packets...
}
System.err.println(ex);
}
IT
// the next line will fail and drop into the catch block if
// there is already a server running on port i
DatagramSocket server = new DatagramSocket(port);
server.close( );
}
PT
} // end try
} // end for
}
}
Phng thc ny cho php gi gi tin UDP qua mng. V d chong trnh sau nhn mt chui t
bn phm, to gi tin gi v gi ti server.
//UDPDiscardClient.java
import java.net.*;
import java.io.*;
public class UDPDiscardClient {
public final static int DEFAULT_PORT = 9;
public static void main(String[] args) {
String hostname;
int port = DEFAULT_PORT;
if (args.length > 0) {
hostname = args[0];
try {
port = Integer.parseInt(args[1]);
}
catch (Exception ex) {
// use default port
}
}
else {
hostname = "localhost";
}
try {
InetAddress server = InetAddress.getByName(hostname);
BufferedReader userInput
= new BufferedReader(new InputStreamReader(System.in));
DatagramSocket theSocket = new DatagramSocket( );
while (true) {
IT
PT
theSocket.send(theOutput);
}
}
// end while
// end try
// end main
Phng thc nhn gi tin UDP qua mng. V d chng trnh sau s to i tng
DatagramSocket vi s cng xc nh, nghe nhn gi d liu gi n, hin th ni dung gi tin v
a ch, s cng ca my trm gi gi tin.
//UDPDiscardServer.java
import java.net.*;
import java.io.*;
public class UDPDiscardServer {
public final static int DEFAULT_PORT = 9;
public final static int MAX_PACKET_SIZE = 65507;
public static void main(String[] args) {
int port = DEFAULT_PORT;
byte[] buffer = new byte[MAX_PACKET_SIZE];
try {
port = Integer.parseInt(args[0]);
}
catch (Exception ex) {
// use default port
}
try {
IT
server.receive(packet);
PT
System.err.println(ex);
}
} // end while
}
// end try
catch (SocketException
ex) {
System.err.println(ex);
}
}
// end catch
// end main
void
void
connect(SocketAddress addr)
Kt ni socket vi a ch socket t xa.
void
disconnect()
Hu b kt ni
boolean
isBound()
Tr v trng thi kt ni ca socket.
boolean
isClosed()
Kim tra socket ng hay cha
boolean
isConnected()
Kim tra trng thi kt ni
PT
IT
void
ng socket, gii phng cc ti nguyn khc, kt thc chng trnh nu cn, khng quay
v bc 3.
ng socket, gii phng cc ti nguyn khc, kt thc chng trnh nu cn, khng quay
v bc 3.
3.3. Mt s lu :
Chng trnh server phi chy trc chng trnh client v chng trnh client phi gi
gi tin n server trc. t gi tn nhn c pha server, server mi tch c a ch
v s hiu cng pha client , t mi to gi tin gi cho client.
4. Mt s chng trnh v d
4.1. Chng trnh minh ho
PT
//UDPEchoClient.java
IT
import java.net.*;
import java.io.*;
}
catch (SocketException ex) {
System.err.println(ex);
}
}
// end main
}
//UDPEchoServer.java
import java.net.*;
import java.io.*;
public class
extends UDPServer {
IT
PT
System.err.println(ex);
}
catch (SocketException ex) {
System.err.println(ex);
}
}
}
IT
C php:
public static NetworkInterface getByName(String name)
throws SocketException
PT
NetworkInterface ni = NetworkInterface.getByName("eth0");
if (ni == null) {
eth0" );
}
}
catch (SocketException ex) {
C php:
public static NetworkInterface getByInetAddress(InetAddress address)
throws SocketException
Phng thc ny tr v i tng NeworkInterface biu din giao tip mng c gn vi vi
mt a ch IP c th, Nu khng c giao tip mng gn vi a ch IP trn my trm cc b
th n tr v null. Khi xy ra li n nm tr v ngoi l SocketException. v d on chng
trnh sau minh ho cch s dng phng thc tm giao tip mng i vi a ch loopback cc
b:
try {
InetAddress local = InetAddress.getByName("127.0.0.1");
NetworkInterface ni = NetworkInterface.getByName(local);
if (ni == null) {
System.err.println("That's weird. No local loopback address.");
IT
}
}
PT
C php:
interfaces.nextElement(
}
}
}
IT
Phng thc tr v tn "thn thin" hn ca mt giao tip mng c th. Trong mng Unix, n
tr v chui ging nh phng thc getName(), Trong mng Windows, no tr v chui tn "thn
thin" nh "Local Area Connection" hoc "Local Area Connection 2".
PT
Ngi s dng cng c th s dng NetworkInterface nhn bit giao tip cc b m mt nhm
multicast c ghp ni, v d:
NetworkInterface nif = NetworkInterface.getByName("bge0");
MulticastSocket() ms = new MulticastSocket();
ms.joinGroup(new InetSocketAddress(hostname, port) , nif);
IT
PT
Name: lo0
java.io.*;
java.net.*;
java.util.*;
static java.lang.System.out;
IT
PT
IT
PT
InetAddress: /129.156.225.59
Up? true
Loopback? false
PointToPoint? false
Supports multicast? false
Virtual? false
Hardware address: [0, 3, 4, 5, 6, 7]
MTU: 1500
IT
import java.util.Enumeration;
import java.net.*;
PT
Enumeration<NetworkInterface>
NetworkInterface.getNetworkInterfaces();
interfaceList
if (interfaceList == null) {
"
((address
instanceof
Inet4Address
getting
network
interfaces:"
}
// Get name(s)/address(es) of hosts given on command line
for (String host : args) {
try {
System.out.println(host + ":");
InetAddress[] addressList = InetAddress.getAllByName(host);
for (InetAddress address : addressList) {
address.getHostName()
"/"
IT
System.out.println("\t"
+
address.getHostAddress());
}
} catch (UnknownHostException e) {
PT
Chng trnh pha client UDP phi hin giao din ha, trong c mt text
nhp username, mt text nhp password, v mt nt nhn Login.
Ti pha server, mi khi nhn c thng tin ng nhp gi t client, n s tin hnh
kim tra trong c s d liu xem c ti khon no trng vi thng tin ng nhp nhn
c hay khng.
Sau khi c kt qu kim tra (ng nhp ng, hoc sai), server UDP s gi kt qu
ny v cho client tng ng, theo ng giao thc UDP.
pha client, sau khi nhn c kt qu ng nhp (ng nhp ng, hoc sai) t
server, n s hin th thng bo tng ng vi kt qu nhn c: nu ng nhp
ng th thng bo login thnh cng. Nu ng nhp sai th thng bo l
username/password khng ng.
PT
IT
Lp User: l lp tng ng vi thnh phn model (M), bao gm hai thuc tnh
username v password, cc hm khi to v cc cp getter/setter tng ng vi cc
thuc tnh.
PT
IT
S lp ca pha server c thit k theo m hnh MVC trong Hnh 2.8, bao gm 3 lp chnh
tng ng vi s M-V-C nh sau:
-
IT
PT
3. Lp ClientControl gi thng tin cha trong i tng User ny sang pha server
kim tra ng nhp
4. Bn pha server, khi nhn c thng tin ng nhp trong i tng User, n s
gi phng thc checkLogin() km tra thng tin ng nhp trong c s d liu.
5. Kt qu kim tra s c tr v cho lp ClientControl
6. pha client, khi nhn c kt qu kim tra ng nhp, lp ClientControl s
chuyn cho lp LoginView hin th bng phng thc showMessage()
7. Lp LoginView hin th kt qu ng nhp ln cho ngi dng
5.3 Ci t
5.3.1 Cc lp pha client
User.java
package udp.client;
import java.io.Serializable;
public class User implements Serializable{
private String userName;
private String password;
public User(){
}
ClientView.java
IT
PT
package udp.client;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
content.add(btnLogin);
this.setContentPane(content);
this.pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
}
public User getUser(){
User model = new User(txtUsername.getText(), txtPassword.getText());
return model;
}
IT
PT
ClientControl.java
package udp.client;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
IT
PT
new ByteArrayInputStream(receiveData);
ObjectInputStream ois = new ObjectInputStream(bais);
result = (String)ois.readObject();
} catch (Exception ex) {
view.showMessage(ex.getStackTrace().toString());
}
return result;
}
}
ClientRun.java
package udp.client;
PT
IT
ServerControl.java
package udp.server;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import udp.client.User;
private
private
private
private
private
ServerView view;
Connection con;
DatagramSocket myServer;
int serverPort = 5555;
DatagramPacket receivePacket = null;
IT
try {
Class.forName(dbClass);
con = DriverManager.getConnection (dbUrl, username, password);
}catch(Exception e) {
view.showMessage(e.getStackTrace().toString());
}
}
PT
IT
ByteArrayInputStream bais =
new ByteArrayInputStream(receiveData);
ObjectInputStream ois = new ObjectInputStream(bais);
user = (User)ois.readObject();
} catch (Exception ex) {
view.showMessage(ex.getStackTrace().toString());
}
return user;
PT
}
}
ServerRun.java
package udp.server;
public class ServerRun {
public static void main(String[] args) {
ServerView view
= new ServerView();
ServerControl control = new ServerControl(view);
}
}
5.5 Kt qu
PT
Login li:
IT
IT
MulticastSocket(SocketAddress bindaddr)
To socket muticast v gn vi socket mt a ch socket c th.
Cc phng thc ca lp MulticastSocket
PT
InetAddress getInterface()
Ly a ch giao tip mng c s dng cho cc gi tin multicast
boolean getLoopbackMode()
Ly chui thit t i local loopback ca gi tin multicast
NetworkInterface getNetworkInterface()
Ly tp giao tip mng multicast
int getTimeToLive()
Ly tham s time to live mc nh ca cc gi tin multicast gi ra
socket
byte getTTL()
Ly tham s time- to -live
void joinGroup(InetAddress mcastaddr)
Ghp nhm multicast
void joinGroup(SocketAddress mcastaddr,
NetworkInterface netIf)
Ghp nhm multicast c th ti giao tip mng c th
void leaveGroup(InetAddress mcastaddr)
Loi b mt nhm multicast
void leaveGroup(SocketAddress mcastaddr,
NetworkInterface netIf)
Loi b mt nhm multicast trn giao tip mng cc b c ch
ra.
IT
PT
Khi gi thng ip ti group, tt c cc my trm pha nhn l cc thnh vin ca nhm s nhn
c gi tin, loi b nhm, phng thc leaveGroup() s c gi.
2. Mt s v d gi/nhn d liu multicast
2.1. V d gi d liu multicast
import java.net.*;
// Which port should we send to
int port = 5000;
// Which address
String group = "225.4.5.6";
// Which ttl
PT
IT
int ttl = 1;
// Create the socket but we don't bind it as we are only going to send data
MulticastSocket s = new MulticastSocket();
// Note that we don't have to join the multicast group if we are only
// sending data and not receiving
// Fill the buffer with some data
byte buf[] = byte[10];
for (int i=0; i<buf.length; i++) buf[i] = (byte)i;
// Create a DatagramPacket
DatagramPacket pack = new DatagramPacket(buf, buf.length,
InetAddress.getByName(group), port);
// Do a send. Note that send takes a byte for the ttl and not an int.
s.send(pack,(byte)ttl);
// And when we have finished sending data close the socket
s.close();
2.2. V d nhn d liu multicast
import java.net.*;
// Which port should we listen to
int port = 5000;
// Which address
String group = "225.4.5.6";
// Create the socket and bind it to port 'port'.
MulticastSocket s = new MulticastSocket(port);
// join the multicast group
s.joinGroup(InetAddress.getByName(group));
// Now the socket is set up and we are ready to receive packets
// Create a DatagramPacket and do a receive
byte buf[] = byte[1024];
DatagramPacket pack = new DatagramPacket(buf, buf.length);
s.receive(pack);
// Finally, let us do something useful with the data we just received,
// like print it on stdout :-)
System.out.println("Received data from: " + pack.getAddress().toString() +
":" + pack.getPort() + " with length: " +
pack.getLength());
System.out.write(pack.getData(),0,pack.getLength());
System.out.println();
// And when we have finished receiving data leave the multicast group and
// close the socket
s.leaveGroup(InetAddress.getByName(group));
s.close();
2.3. Mt s v d khc
//MulticastJoin.java
import java.net.*;
import java.io.*;
public class MulticastJoin {
public static void main(String [ ] args){
try {
MulticastSocket mSocket = new MulticastSocket(4001);
PT
IT
//MulticastListener.java
import java.net.*;
import java.io.*;
public class MulticastListener {
public static void main( String [ ] args) {
InetAddress mAddr=null;
MulticastSocket mSocket=null;
final int PORT_NUM= 4001;
try {
mAddr = InetAddress.getByName("audionews.mcast.net");
mSocket = new MulticastSocket(PORT_NUM);
String hostname = InetAddress.getLocalHost().getHostName();
byte [ ] buffer = new byte[8192];
mSocket.joinGroup(mAddr);
System.out.println("Listening from " + hostname + " at " +
mAddr.getHostName());
while (true){
DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
mSocket.receive(dp);
String str = new String(dp.getData(), "8859_1");
System.out.println(str);
}//end of while
}
catch (SocketException se) {
System.out.println("Socket Exception : " + se);
}
catch (IOException e) {
System.out.println("Exception : " + e);
}
finally {
if (mSocket != null){
try {
mSocket.leaveGroup(mAddr);
mSocket.close();
}
catch (IOException e){ }
}//end of if
}//end of finally
}//end of main
}
VII. KT LUN
PT
IT
CHNG III
K THUT XY DNG NG DNG MNG PHA SERVER
I. GII THIU V CC KIU SERVER
Trong m hnh client/server, chng trnh server ng vai tr phc v yu cu gi ti t chng
trnh client. Chng trnh server c th phc v mt hoc nhiu client ng thi hoc phc v
kiu lp.
Server c th phn thnh cc loi sau:
Server chy ch ng thi hng khng kt ni(TCP)
Server chy ch lp hng khng kt ni(TCP)
Server chy ch ng thi hng khng kt ni(UDP)
Server chy ch lp hng khng kt ni(UDP)
v s phn loi ny c th hin nh hnh 3.
PT
Hng kt ni
(TCP)
IT
SERVER
Kiu ng
thi
Kiu lp
(Tun t)
Hng khng
kt ni(UDP)
Kiu ng
thi
Kiu lp
(Tun t)
client . Cn server chnh s tip tc t trng thi nghe tn hiu kt ni khc.Server cng c
th s dng b m cho mi kt ni. Cc segment truyn t client ti s c ct vo b m ph
hp v s c phc v ng thi bi server. M hnh hot ng ca server ny c th hin
nh hnh 3.2.
Client
Parrent
server
Port
Child
server
Child
server
Child
server
Well-known
TCP
Port
Client
TCP
Client
TCP
TCP
PT
Port
IT
Port
Xy dng chng trnh a tin trnh: Trong chng trnh ny tin trnh cha s sinh ra tin
trnh con mi khi c mt client gi yu cu ti server. Nhc im ca k thut lp trnh ny l
khng tn dng hiu qu CPU. V khi chng trnh chy, n phi s dng c ch ngt
chuyn t tin trnh ny sang tin trnh khc, nn CPU s rnh ri trong qu trnh ny.
Client
Port
server
UDP
Well-known
Port
Client
Port
UDP
Client
UDP
PT
Port
IT
UDP
Hnh
PT
IT
PT
IT
to mt lung mi:
to lung mi c 2 cch khai bo:
Cch 1: Khai bo mt lp k tha lp Thread, t ci t m lnh thc thi ca lung
vo phng thc run() bng cch khai bo np chng phng thc run.
V d:
Vit chng trnh sinh ra 10 lung, mi lung in ra s th t ca lung.
//TestThread.java
class NewThread extends Thread
{
private int count;
//Khai bao cau tu
NewThread(int count)
{
super();
this.count=count;
start();
}
public void run()
{
System.out.println("Luong thu:"+count);
}}
class TestThread{
public static void main(String[] args)
{
int i=0;
while(i<10)
{
new NewThread(i);
i++;
}
}}
sleep()
Blocked
suspend()
new Thread
wait()
resume()
start()
Runnable
notify()
stop()
Dead
IT
PT
Cch 2: Khai bo lp thc thi giao din Runnable. Lp ny cho php to ra i tng
Thread v ci t phn thn cho phng thc run() ca giao din. V d vit li chng
trnh trn, chng trnh ch khc phn khai bo lp NewThread.
//TestThread.java
class NewThread implmnts Runnable
{
private int count;
//Khai bao cau tu
NewThread(int count)
{
Thread t=new Thread();
this.count=count;
public void start()
{ run(); }
public void run()
{
System.out.println("Luong thu:"+count);
}}
Mt vn quan trng khc l vn ng b. gii quyt vn ny Java s dng mt c
ch c bit gi l Monitor.
3. Xy dng chng trnh server phc v nhiu client ng thi hng kt ni
minh ho k thut ny, chng ta tin hnh xy dng mt chng trnh v d:
Hy vit chng trnh server phc v nhiu client ng thi s dng giao thc truyn thng TCP.
Chng trnh cho php nhn bn knh ng trn gi n t cc client, tnh din tch hnh trn,
hin th tn, a ch IP, s cng, bn knh r, din tch ca client tng ng. Sau tr kt qu v
cho client.
a) Chy chng trnh s dng trnh telnet
b) Vit chng trnh client.
vit chng trnh ny chng ta s s dng k thut a lung trong Java. Mi khi mt chng
trnh client gi yu cu kt ni n, server s sinh ra mt lung mi phc v kt ni . Sau
khi phc v xong kt ni no th lung c gii phng. M hnh xy dng chng trnh th
hin nh hnh 3.5.
Server
S1
r1
S2
Sn
r2
rn
Client_2
r1
r2
IT
Client_1
Client_n
PT
//areaClient.java
import java.io.*;
import java.net.*;
class areaClient{
public static void main(String[] args)
{
//Khai bao bien
Socket cl=null;
BufferedReader inp=null;//luong nhap
PrintWriter
outp=null.//luong xuat
BufferedReader key=null;//luong nhap tu ban phim
String ipserver= "127.0.0.1";//Chuoi dia chi server
int
portserver=3456; //dia chi cong server
rn
PT
IT
String
r; //ban kinh r la chuoi so
//Tao socket va ket noi toi server
try{
cl=new Socket(ipserver,portserver);
//tao luong nha/xuatp kieu ky tu cho socket
inp=new BufferedReader(new InputStreamReader(cl.getInputStream()));
outp=new PrintWriter(cl,getOutputStream(),true);
//tao luong nhap tu ban phim
key=new BufferedReader(new InputStreamReader(System.in));
//Nhap ban kinh r tu ban phim
System.out.print("r=");
r=key.readLine().trim();
//gui r toi server
outp.println(r);
//Nhan dien tich tra ve tu server va hien thi
System.out.println("Area:"+inp.readLine());
//ket thuc chuong trinh
if(inp!=null)
inp.close();
if(key!=null)
key.close();
if(outp!=null)
outp.close();
if(cl!=null)
cl.close();
}
cacth(IOException e)
{
System.out.println(e);
}
}
}
PT
IT
class NewThread
extends
Thread
{
private
int count;
private Socket cl=null;
private BufferedReader inp=null;//luong nhap
private PrintWriter
outp=null;//luong xuat
NewThread(Socket
cl, int count)
{
super();//Truy xut cu t lp Thread
this.cl=cl;
this.count=count;
start();
}
//cai dat phuong thuc run-Luong moi
public void
run()
{
try{
//tao luong nhap /xuat cho socket cl
inp=new BufferedReader(new InputStreamReader(cl.getInputStream()));
outp=new PrintWriter(cl.getOutputStream(),true);
//Doc ban kinh gui toi tu client
double r=Double.parseDouble(inp.readLine().trim());
// lay dia chi client
InetAddress addrclient=cl.getInetAddress();
//lay so cong phia client
int
portclient=cl.getPort();
//Tinh dien tich
double area=3.14*r*r;
//Hien thi
System.out.println("Luong
thu:"+count+",
client:"+addrclient.getHostName()+
", ip:"+addrclient.getHostAddress()+",port:"+portclient+
", r="+r+",area:"+area);
//Gui dien tich ve cho client tuong ung
outp.println(area);
//ket thuc luong
inp.close();
outp.close();
cl.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
//Chuong trinh server
class
AreaThreadServer{
public static void main(String[] args)
{
IT
PT
IT
PT
PT
IT
CHNG IV
LP TRNH VI GIAO THC DCH V MNG PHA CLIENT
I. GII THIU
Chng ny s hng sinh vin s dng k thut lp trnh socket c trang b trong cc
chng trc lp trnh vi mt s giao thc dch v mng ph bin trn internet nh: DSN,
Telnet, FTP, TFTP, SMTP, POP3, IMAP4, HTTP, RTP.
lp trnh c vi cc giao thc truyn thng c sn, ngi lp trnh phi:
Thng qua sinh vin nm c k thut lp trnh vi cc giao thc truyn thng c sn khc
pht trin cc ng dng hoc pht trin cc modul tch hp gii quyt cc bi ton thc t.
IT
PT
PT
IT
i vi lp trnh ng dng mng, bi ton quan trng nht l xy dng chng trnh phn
mm pha client. iu ny cho php ngi s dng c th to ra c phn mm vi giao
din ph hp v d dng tch hp vi cc dch v khc. lp trnh oc dch v Telnet pha
ngi s dng,ngi lp trnh phi nm chc tp k t NVT, cc tu chn v cc chnh sch
tho thun tu chn ca Telnet, cc lnh iu khin server v cu trc lnh Telnet. Cui
cng ngi s dng phi nm c cc ch hot ng ca Telnet trc khi ci t chng
trnh Telnet.
2. Mt s kin thc giao thc Telnet c bn
2.1. Tp k t chung NVT
to ra s c lp gia my tnh cc b v my tnh t xa trong cc mng khng ng nht,
telnet nh ngha mt giao din chung gi l tp k t mng u cui o NVT (Network Virtual
Terminal). NVT gm 2 tp k t:
Tp k t d liu: c bit cao nht bng 0 v c m thuc [0,127] .
Tp k t iu khin: c bit cao nht bng 1 v c m thuc [128,255] .
Code
Decimal Value
Function
NULL
NUL
No operation
Line Feed
LF
10
Carriage
CR
13
BELL
BEL
PT
Return
Back Space
IT
Name
BS
HT
Vertical Tab
VT
11
Tng t nh HT
Form Feed
FF
12
Horizontal
Tab
Name
Decimal Code
Meaning
240
NOP
241
DM
242
BRK
243
Break: ch ra s thot
IP
244
AO
245
Abort output: cho php tin trnh hin thi chy hon thnh
nhng khng gi u ra ca n cho ngi s dng
AYT
246
EC
247
EL
248
GA
249
PT
IT
SE
250
251
252
253
DONT
254
IAC
255
SB
WILL
WONT
DO
Binary : cho php ngi nhn dch mi k t 8 bit nh l d liu nh phn, tr k t IAC
Echo: cho php Server phn hi d liu nhn c tr li client hin ln mn hnh
Suppress go head : loi b k t CA
Timing: cho php mt thnh vin pht sinh du hiu nh thi, ch th rng tt c d liu nhn
c trc c x l. M ca cc tu chn c th hin trong bng sau:
Name
RFC
Echo
857
Suppress go ahead
858
Status
859
Timing mark
860
24
Terminal type
1091
31
Window size
1073
32
Terminal speed
1079
33
1372
34
Linemode
1184
36
Environment variables
1408
PT
IT
Decimal Code
Trong Telnel trc khi s dng mt ty chn no th gia Client v Server phi c tha thun
v ty chn . C hai phng thc tha thun l: ngh v yu cu.
Vi hai hnh thc ny th c hai kiu tha thun:
Cho php mt ty chn
Lm mt hiu lc mt ty chn
Cc lnh dng trong tha thun ty chn:WILL, DO, WONT, DONT
2.4. S nhng trong telnet
Trong telnet gi cc lnh v d liu th s dng mt kt ni duy nht, cc lnh c nhng
trong dng d liu bn nhn phn bit c lnh vi d liu trc mi k t iu khin u c
k t IAC. Trong trng hp c 2 k t IAC i lin nhau th k t IAC th nht s b b qua v k
t IAC th hai s l d liu.
2.5. Cc ch lm vic ca Telnet
Socket
telnetclient=new
IT
Thc hin gi/ nhn cc lnh ca Telnet thing qua lung nhp/xut
v d khi tho thun, client cn phi gi lnh WONT c m l 252, IAC l 255 vi lnh:
PT
if(c2==255)
{
IT
addMouseListener(new MouseAdapter() {
requestFocus();
PT
});
Graphics g=getGraphics();
if (c=='\r')
{
// Return
for (int i=lines-1; i>0; --i)
text[i]=text[i-1];
text[0]="";
update(g);
}
// Cc k t iu khin: backspace, delete, telnet EC
else if (c==8 || c==127 || c==247)
{
int len=text[0].length();
if (len>0)
{
--len;
text[0]=text[0].substring(0, len);
g.setColor(getBackground());
g.fillRect(len*charWidth+margin, getSize().height-margin-charHeight,
(len+1)*charWidth+margin, getSize().height-margin);
}
}
else if (c=='\t')
{
text[0]+="
";
text[0].substring(0, text[0].length()&-8);
}
else if (c>=32 && c<127)
{
// K t c th in
g.drawString(""+c, margin+text[0].length()*charWidth,
text[0]+=c;
}
g.dispose();
}
IT
getSize().height-margin);
PT
int height=getSize().height;
for (int i=0; i<lines; ++i)
}
}
}
// c cc k t v gi n u cui
public void run()
{
while (true)
{
try {
int c=in.read();
if (c<0)
{
// EOF
int c2=in.read();
// option
if (c1==253)
IT
int c1=in.read();
PT
terminal.put((char)c);
}
catch (IOException x) {
System.out.println("Receiver: "+x);
}}}}
// Set title\
trn
add(terminal=new Terminal());
// X l vic ng ca s
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
dispose();
try {
out.close();
}
catch (IOException x) {
System.out.println("Closing connection: "+x);
}
}
public void windowClosed(WindowEvent e) {
System.exit(0);
}
IT
});
// X l cc thao tc vi bn phm
terminal.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char k=e.getKeyChar();
PT
try {
terminal.put(k);
out.write((int)k);
if (k=='\r')
{
out.write('\n');
// Convert CR to CR-LF
out.flush();
}
}
catch (IOException x) {
System.out.println("Send: "+x);
}}});
try {
// M mt connection
System.out.println("Opening
connection
to
"+hostname+"
"+port);
Socket socket=new Socket(hostname, port);
InetAddress addr=socket.getInetAddress();
System.out.println("Connected to "+addr.getHostAddress());
in=socket.getInputStream();
on
port
out=socket.getOutputStream();
// Hin th ca s
pack();
setVisible(true);
// Bt u nhn d liu t server
new Receiver(in, out, terminal);
System.out.println("Ready");
}
catch (UnknownHostException x) {
System.out.println("Unknown host: "+hostname+" "+x);
System.exit(1);
}
catch (IOException x) {
System.out.println(x);
System.exit(1);
// Chng trnh chnh
public class TelnetClient
{
IT
}}}
PT
hostname=argv[0];
if (argv.length>1)
port=Integer.parseInt(argv[1]);
catch (ArrayIndexOutOfBoundsException x) {
FTP s dng 2 kt ni truyn thng ng thi tng hiu qu ca vic truyn tp qua
mng:
IT
PT
IT
PT
IT
PT
1.2.1.2. Tp p ng(response)
IT
p ng FTP c gi t FTP server v client sau mi khi FTP server thc thi mt lnh FTP gi
t client n server. C php ca mt p ng ca FTP c dng sau:
PT
IT
PT
PT
IT
Thit lp v hu b kt ni iu khin.
Nm chc trnh t c th thc hin download hoc upload tp s dng giao thc
FTP.
IT
InputStreamReader(connectionSocket.getInputStream()));
PT
if (!isPositiveCompleteResponse(getServerReply())){
disconnect();
return false;
}
return true;
PT
IT
{
return readDataToFile("retr " + fileName, fileName);
}
public boolean downloadFile(String serverPath, String localPath)
throws IOException
{
return readDataToFile("retr " + serverPath, localPath);
}
Mt s phng thc thc hin cc lnh FTP c lit k trong bng sau:
STT
2
3
4
5
IT
Phng thc ci t
Lnh FTP
CD
RNFR,
RNTO
RMD
DELE
PWD
PT
PT
IT
Giao thc SMTP c thit k da vo m hnh giao tip sau: khi c yu cu t user v
dch v mail, bn gi Sender-SMTP thit lp mt knh truyn hai chiu ti bn nhn
Receiver-SMTP v Receiver-SMTP gi p ng tr li cho Sender-SMTP
IT
PT
IT
PT
IT
PT
Nhng lnh SMTP nh ngha s truyn mail hay chc nng ca h thng mail c yu
cu bi user. Nhng lnh SMTP l nhng chui k t kt thc bng <CRLF>. Bn thn
m lnh l nhng k t ch (alphabetic) kt thc bi <SP> nu c nhng tham s theo sau
v nu khng c th <CRLF>. C php ca nhng mailbox phi tun theo nhng quy c
ca receiver.
Mt phin giao dch mail cha ng mt vi i tng d liu, c truyn nh l nhng
i s cho cc lnh khc nhau. Receiver-path l i s ca lnh MAIL. Forward-path l
i s ca nhng lnh RCPT. V mail data l i s ca lnh DATA. Nhng i s hay
nhng i tng d liu ny c truyn i v duy tr cho n khi truyn xong bi s ch
nh kt thc ca mail data. M hnh hin thc cho cch lm ny l nhng buffer ring
bit c cung cp lu tr kiu ca i tng d liu, l cc buffer: reverse-path,
forward-path, v mail data buffer. Nhng lnh xc nh to ra thng tin c gn vo mt
buffer xc nh , hoc xa bt i mt hay mt s buffer no
IT
PT
MAIL FROM
RCPT TO
DATA
QUIT
Sau mi lnh gi, phi thc hin c cc p ng tr v.
PT
IT
java.io.BufferedReader;
java.io.FileInputStream;
java.io.InputStreamReader;
java.io.PrintStream;
java.net.Socket;
java.util.StringTokenizer;
= null;
=
=
=
=
=
=
"";
"";
"";
"";
"Java is Fun";
null;
IT
SendMail()
{
if(mailLock != null)
{
if(mailLock instanceof Applet)
{
Applet app = (Applet)
}
}
}
*/
PT
{
close("Reply error:"+serverReply);
return;
PT
IT
}
outputStream.println("DATA");
serverReply = inputStream.readLine();
if(serverReply.startsWith("5"))
{
close("DATA Server error : "+serverReply);
return;
}
outputStream.println("From: "+from);
outputStream.println("To: "+to);
if(subject != null)
outputStream.println("Subject: "+subject);
if(replyTo != null)
outputStream.println("Reply-to: "+replyTo);
outputStream.println("");
outputStream.println(mailData);
outputStream.print("\r\n.\r\n");
outputStream.flush();
serverReply = inputStream.readLine();
if(serverReply.startsWith("5"))
{
close("DATA finish server error: "+serverReply);
return;
}
outputStream.println("quit");
serverReply = inputStream.readLine();
if(serverReply.startsWith("5"))
{
close("Server error on QUIT: "+serverReply);
return;
}
inputStream.close();
outputStream.close();
mailSendSock.close();
}
catch(Exception any)
{
any.printStackTrace();
close("send() Exception");
}
close("Mail sent");
}
public boolean open()
{
synchronized(mailLock)
{
try
{
mailSendSock = new Socket(mailServerHost, 25);
outputStream = new PrintStream(mailSendSock.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(
mailSendSock.getInputStream()));
serverReply = inputStream.readLine();
if(serverReply.startsWith("4"))
{
PT
IT
IT
POP3 (Post Office Protocol Version 3) l mt giao thc truy cp hp th. N gm 2 phn mm:
POP3 Server ci trn my ch c cha hp th; POP3 Client ci t trn my cc b. truy cp
c th, ngi s dng dng phn mm truy cp hp th thit lp kt ni ti POP3 Server ti s
cng mc nh l 110. POP3 server s gi tr v cho client mt danh sch cc mc th cha trong
hp th ngi s dng. Giai on s dng giao thc truy cp th c th hin nh hnh v.
PT
IT
PT
thc hin truy cp ly th, chng trnh ly th phi thc hin cc thao tc c bn sau:
To lung nhp/xut
Thc hin gi lnh ti mail server, sau mi lnh gi, n thc hin c p ng tr v
IT
PT
Chng trnh v d sau minh ho cch ci t chng trnh nhn th vi giao thc POP3.
//CheckMail.java
import java.net.*;
import java.io.*;
public class CheckMail {
public static void main(String s[]) {
// CheckMail [mailServer] [user] [password]
try {
CheckMail t = new CheckMail();
int i = t.checkMyMail(s[0], s[1], s[2]);
if (i==0) {
System.out.println("No mail waiting.");
}
else {
System.out.println
("There " + (i==1?"is " :"are ") + i +
" message" +(i==1?"":"s")+ " waiting.");
}
}
catch (Exception e) {
e.printStackTrace();
}
PT
IT
}
private void send(BufferedWriter out, String s) throws IOException {
out.write(s+"\n");
out.flush();
}
private String receive(BufferedReader in) throws IOException {
return in.readLine();
}
private int checkMyMail
(String server, String user, String pass) throws IOException {
Socket s = new Socket(server, 110);
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
receive(in);
send(out, "USER " + user);
receive(in);
send(out, "PASS " + pass);
receive(in);
return getNumberOfMessages(in, out);
}
public int getNumberOfMessages
(BufferedReader in, BufferedWriter out) throws IOException {
int i = 0;
String s;
send(out, "LIST");
receive(in);
while((s = receive(in)) != null) {
if (!(s.equals("."))) {
i++;
}
else
return i;
}
return 0;
}
V. KT LUN
Nh vy trong chng ny bc u cung cp cho ngi lp trnh cch lp trnh vi cc giao
thc truyn thng pht trin sn c thng qua k thut socket. y l chng quan trng, n
va cng c cho sinh vin kin thc mng, va trang b cho sinh vin bit cch ci t cc giao
thc bng mt ngn ng lp trnh c th. Trn c s sinh vin c th hon thin mt dch
v mng hon chnh hoc pht trin cc modul chng trnh tch hp vo cc chng trnh
ung dng khc nhau. Ngoi cc giao thc trn, sinh vin nn lp trnh vi mt s giao thc
Internet ph bin khc nh DNS, TFTP, HTTP, RTP hoc ci t cc giao thc, gi tin ca cc
giao thc TCP, UDP, ICMP, ARP, IP, ICMP hoc kho st pht trin cc ng dng vi h giao
thc Hxxx, SIP...Cui cng mt iu nhn mnh vi ngi hc khi pht trin cc ng dng mng
vi cc giao thc: Phi nm chc m hnh, cu trc, c ch truyn thng ca cc giao thc th
PT
IT
IT
PT
Pha server l pha my tnh t xa cha cc i tng c phng thc cho php gi t xa.
Pha client l pha cha cc i tng pht sinh li gi phng thc t xa.
Mt chng trnh Client c th kch hot cc phng thc xa trn mt hay nhiu Server. Tc l
s thc thi ca chng trnh c tri rng trn nhiu my tnh. y chnh l c im ca cc
ng dng phn tn. Ni cch khc, RMI l c ch xy dng cc ng dng phn tn di ngn
ng Java.
Mi i tng c phng thc cho php gi t xa, trc khi s dng c n phi c ng k
vi my o java thng qua b ng k ca JDK hoc do ngi s dng nh ngha. V mi i
tng cng phi c gn mt chui dng lm tn truy xut tm i tng trn mng.
Chui tn c dng nh URL:
"rmi://<host>[:port]/ObjName"
Trong :
rmi : ch phng thc truy cp
IT
PT
RMI s dng giao thc truyn thng JRMI. Giao thc ny cho php to ra mi trng mng
truyn thng trong sut m t li gi phng thc t xa khng khc g li gi cc b. V
truyn thng, java s dng 2 i tng trung gian ng gi truyn thng v khi phc li li
gi, kt qu thi hnh phng thc t xa qua mng t cc gi tin truyn qua mng .. i tng
_Skel ci pha bn server v _Stub ci pha bn client.
h tr lp trnh RMI, java h tr nhiu lp v giao din th vin m tp trung ch yu trong
2 gi: java.rmi v java.rmi.server.
Nh vy k thut lp trnh phn tn i tng RMI trong java cho php phn tn ti ln cc
my tnh trn mng thay v tp trung trn mt my. iu ny tht s c ngha ln i vi cc
ng dng m c khi lng tnh ton ln m i hi thi gian thc. V mt my tnh c mnh
n my cng vn hu hn. Nht l i vi nhng bi ton thc t nh: Bi ton th trng
chng khon, ngn hng, bi ton hng khng, d bo thi tit, bi ton nghin cu v
tr...Phn sau y chng ta s i su vo nghin cu cc k thut lp trnh ca RMI v c ch
hot ng ca chng.
2.1.. Kin trc ca chng trnh Client Server theo c ch RMI
Hnh 5.1. l kin trc ca mt chng trnh phn tn i tng RMI theo m hnh Client /Server:
Trong :
PT
IT
C ch nh v i tng xa
IT
Hnh 5.2. m t mt ng dng phn tn RMI s dng dch v danh b ly cc tham chiu ti
cc i tng xa.
PT
Client thc thi mt li gi phng thc t xa thng qua i tng Stub (7).
3. Cc lp h tr lp trnh vi RMI
Java h tr cc lp cn thit ci t cc ng dng Client-Server theo kiu RMI trong
cc gi: java.rmi. Trong s cc lp thng c dng l:
java.rmi.Naming:
java.rmi.RMISecurityManager
java.rmi.RemoteException;
java.rmi.server.RemoteObject
java.rmi.server.RemoteServer
java.rmi. server.UnicastRemoteObject
IT
PT
4. Khi to ng dng
1. K thut lp trnh RMI
Chng trnh server: c i tng c phng thc cho php gi t xa int add(int
x,int y) tnh tng ca 2 s.
Chng trnh client: cho php gi phng thc th xa add() qua mng tnh
tng ca 2 s nguyn v hin th kt qu.
IT
java.rmi.*;
public int
}
TT
extends
PT
public interface
add(int x,int
Remote
y) throws
RemoteException;
import java.rmi.*;
class
TTImpl
implements
TT
{
public int add(int x,int y) throws
RemoteException
{
return
(x+y);
}
}
Bc 3: Xy dng chng trnh server. Chng trnh server phi thc hin 3 vn ct li sau
y:
c=new TTImpl();
//TTServer.java
import java.rmi.*;
IT
import java.rmi.serrver.*;
PT
class TTServer{
try{
c=new
TTImpl();
UnicastRemoteObject.exportObject(c);
//Gan chuoi URL
Naming.bind(rmi://localhost/Obj, c);
System.out.println(Server RMI da san sang....);
}
catch(Exception
e)
{
System.out.println(e);
}
}}
Truy xut tm i tng c phng thc cho php gi t xa thng qua chui tn URL a
c chng trnh server gn cho i tng. Bng cch client s dng phng thc
lookup() ca lp Naming hi b ng k thng qua s cng c th c nh ngha
trong chui URL. Nu tm thy, server s tr v tham chiu n i tng t xa c kiu
giao din ca i tng.
Gi thi hnh phng thc t xa thng qua bin tham chiu ti i tng t xa.
try{
TT
IT
x=(TT)Naming.lookup(rmi://localhost/Obj);
cua
a=+a+
voi
b=+b+
la
PT
System.out.println(Tong
s=+x.add(a,b));
}
catch(Exception e)
{
System.out.println(e);
}
}}
---------------------------->TT.class
(1)
TTImpl.java ---------------------------->TTImpl.class
(2)
TTServer.java ---------------------------->TTServer.class
(3)
TTClient.java ----------------------------->TTClient.class
(4)
Bc th 2: Pht sinh cc tp i tng trung gian _stub v _skel bng cch s dng
trnh dch rmic.exe ca JDK dch tp i tng c phng thc cho php gi t xa TTImpl:
rmic
TTImpl
[Enter]
(5)
TTImpl_Skel.class
(6)
[porrt]
[Enter]
PT
java TTServer
IT
[Enter]
Sau khi thc hin xong, sa li chng trnh client phn a ch host trong chui URL, dch li v
c th chy th qua mi trng mng. Khi ca s 1, 2 chy phia bn server, ca s 3 chy
pha client.
III. C CH TRUYN THNG RMI
C ch truyn thng RMI c th gii thch theo hnh 5.3 v n thc hin theo cc bc sau:
Step 1: u tin i tng ci t cc phng thc v gi hm Naming.bind() ng k vi b
qun l rmiregistry trn server thng qua qu trnh 1.
Step 2: i tng trn client gi hm Naming.lookup() truy tm i tng t xa bng cch hi
b ng k thng qua chui URL bng qu trnh 2.
TTClient
4
TTImpl
(add())
rmiregistry
TT
6
TTImpl_Skel
TTImpl_Stub
5
IT
PT
Step 5: Khi mt phng thc c gi, li gi s c chuyn ti i tng trung gian _Stub v
c ng gi chuyn qua mng theo giao thc JRMP ti i tng _Skel pha server.
Step 6: i tng Skel pha server s khi phc li li gi v gi thi hnh phng thc t xa
bng qu trnh 6.
Step 7: Sau khi phng thc t xa thi hnh xong, kt qu s c i tng _Skel tr v cho i
tng client bng mt qu trnh truyn thng ngc vi qu trnh trn.
Trong cch truyn i tng theo kiu tham chiu th ch c tham chiu n i tng c
truyn qua mng nn khc phc c hn ch ca truyn i tng theo kiu tham tr. V n cho
php truy xut gi phng thc t xa theo c 2 chiu t client n server v ngc li.
ch th mt i tng truyn cho phng thc t xa qua mng l truyn tham tr hay truyn
tham chiu th trong Java s dng cch ci t nh sau: Tt c cc i tng c kiu lp thc thi
giao din Serializable th khi truyn cho phng thc u c n nh l truyn tham tr. Cn
cc i tng m c kiu lp thc thi giao din Remote th khi truyn cho phng thc t xa s
l truyn tham chiu.
Sau y chng ta s kho st k 2 cch truyn i tng theo kiu tham tr v kiu tham chiu.
2. Truyn i tng theo kiu tham tr
nm c k thut ny, chng ta xt v d sau: Vit chng trnh RMI c cu trc sau:
Pha client cho php to i tng BOX c cc tham s w, h, d tng ng l chiu rng,
chiu cao v chiu su ca hnh hp ch nht. Sau gi phng thc t xa v truyn i
tng BOX cho phng thc theo kiu tham tr, nhn kt qu tr v v hin th.
IT
PT
Bc 1: Xy dng lp BOX thc thi giao din Serializable thuc gi java.io i tng c th
truyn theo kiu tham tr.
//BOX.java
import java.io.*:
class
{
int
BOX
implements
Serializable
w,h,d;
BOX(){
extends
Remote
{
public
BOX
changeObject(BOX
obj) throws
RemoteException;
BBImpl
implements
BB
{
public
BOX
changeObject(BOX
obj) throws
RemoteException
{
obj.w+=10; obj.h+=5; obj.d+=15;
return obj;
}}
IT
import java.rmi.*;
import java.rmi.server.*;
class BBServer{
PT
{
try{
BB
c=new
BBImpl();
UnicastRemoteObject.exportObject(c);
Naming.bind(rmi://localhost/cObj,c);
}
catch(Exception
e)
{
System.out.println(e);
}}}
java.rmi.*;
BBClient{
args)
BB
BOX
c=(BB)Naming.lookup(rmi://localhost/cObj);
box=new
BOX();
System.out.println(w=+box.w+,h=+box.h+,d=+box.d);
box=c.changeObject(box);
System.out.println(w=+box.w+,h=+box.h+,d=+box.d);
}
catch(Exception e)
{
System.out.println(e);
}
}}
IT
Sau khi to chng trnh xong, thc hin dch v chy chng trnh theo k thut c trnh
by phn trn. r hn, cc bn c th hin th kch c ca i tng BOX pha client, hin
th kch c i tng sau khi gi phng thc t xa pha server so snh.
3. Truyn i tng theo kiu tham chiu
Trong k thut ny, i tng pha bn client v server u c th gi phng thc t xa ca
nhau v khc vi k thut trun tham s trn l ch truyn tham chiu n i tng thay v
truyn bn thn i tng.
PT
i tng client
i tng server
Gi phng thc
Gi phng thc
AtClient
extends
Remote
{
public void callClientMethod(String msg) throws
RemoteException;
AtServer
extends
Remote
{
c)throws
RemoteException;
IT
PT
import java.rmi.*;
class AtClientImpl
{
public void
{
implements
AtClient
System.out.println(msg);
}}
//AtServerImpl.java
import java.rmi.*;
class AtServerImpl
implements
AtServer
{
AtClient client;
public void registerClient(AtClient c) throws RemoteException{
client=c;
}
public void
{
System.out.println(msg);
for(int i=0;i<10;i++){
String msg=Server response
+Math.random()*1000;
client.callClientMethod(msg);
}}}
rServer{
server=new
AtServerImpl();
IT
UnicastRemoteObject.exportObject(server);
Naming.bind(rmi://localhost/serverObject,server);
System.out.println(Waiting for client request...);
}}
PT
import java.rmi.*;
import java.rmi.server.*;
class
rClient{
AtClient
cl=new
AtClientImpl();
UnicastRemoteObject.exportObject(cl);
Naming.bind(rmi://localhost/clObject, cl);
AtServer svr=(AtServer)Naming.lookup(rmi://localhost/serverObject);
svr.registerClient(cl);
svr.callServerMethod(Client contact server);
}}
Dch:
D:\rmi\>javac *.java
`
D:\rmi\>rmic AtServerImpl
D:\rmi\>rmic AtClientImpl
PT
IT
Chng ta bit, mt i tng c phng thc cho php gi t xa trwcs khi s dng phi ng
k i tng vi my o java thng qua trnh rmiregistry, sau phi gn mt chui URL pha
server v pha client phi c lnh tm kim thng qua URL . i vi chng trnh n gin, t
i tng th khng vn g. Nhng khi pha Server c hng trm, hng nghn v hn na cc
i tng c phng thc cho php gi t xa thi vn tr nn nghim trng. Khi trnh
rmiregistry phi qun l qua nhiu i tng, ngi lp trnh chng trnh client phi nh nhiu
i tng, s cu lnh ng k i tng, gn chui URL pha server(bind()) v cu lnh tm
kim pha client(lookup()) qu nhiu, tng tc qua mng qu nhiu, t chng trnh tr nn
phc tp. gii quyt vn ny, rmi c mt k thut cc k hu ch. l, thay v to truy
xut, nh nhiu i tng th by gi ngi lp trnh ch cn nh mt i tng, ch cn ng k
vi my o java mt i tng v ch cn truy tm mt i tng. Cn tt c cc i tng cn
li s do i tng i din ny to ra, ang k v cho php pha client ch cn gi cc phng
thc t xa ca i tng i din tr v tham chiu n cc i tng do n sn sinh ra. i
tng gi l i tng sn sinh nhiu i tng(Factory Object). Hnh 5.5. cho chung ta thy
c ch s dng mt i tng(Factory Object) sn sinh nhiu i tng khc(A, B, C). C ch
s dng i tng Factory sn sinh nhiu i tng khc c thc hin nh sau:
Trnh client mun gi i tng A, B, C; trc ht trnh client phi lin h vi rmiregistry
ly v tham chiu n i tng Factory Object.
Sau khi c tham chiu n i tng Factory Object, trnh client thc hin Factory Object
yu cu to ra cc i tng A, B, C, ng k cc i tng A, B, C vi my o java
v tr v tham chiu n A, B, C cho client.
Pha Client
Pha Server
rmiregistry
Factory
Object
Client
Object A
Object B
Object C
IT
PT
import java.rmi.*;
public interface
{
public String
AA
extends
get_A()
throws
Remote
RemoteException;
}
//BB.java
import java.rmi.*;
public interface
{
public String
}
//CC.java
BB
extends
get_B()
throws
Remote
RemoteException;
import java.rmi.*;
public interface
{
public String
CC
extends
get_C()
Remote
throws
RemoteException;
AAImpl
public String
return
implements
get_A()
AA{
throws
RemoteException{
}}
//BBImpl.java
class
BBImpl
public String
return
IT
import java.rmi.*;
implements
get_B()
BB{
throws
RemoteException{
}}
PT
//CCImpl.java
import java.rmi.*;
class
CCImpl
public String
return
}}
implements CC{
get_C()
throws
RemoteException{
Bc 3: Khai bo giao din FF, trong giao din ny khai bo cc phng thc getRef_X() tr
v cc tham chiu n i tng A, B, C
//FF.java
import
java.rmi.*;
public interface
FF
extends
Remote{
public AA
getRef_A() throws
RemoteException;
public BB
getRef_B() throws
RemoteException;
public CC
getRef_C() throws
RemoteException;
Bc 5: Khai bo lp FFImpl thc thi giao din FF. Trong lp ny phi thc hin cc cng vic
sau:
java.rmi.*;
import
java.rmi.serrver.*;
class
FFImpl
implements
FF{
a=new
AAImpl();
BB
b=new
BBImpl();
CC
c=new
CCImpl();
//Khai bao cau tu FFImpl, trong do thuc hien dang ky cac doi tuong
FFImpl()
IT
{
try{
UnicastRemoteObject.exportObject(a);
UnicastRemoteObject.exportObject(b);
PT
UnicastRemoteObject.exportObject(c);
}catch(Exception
{}
}
e)
getRef_A() throws
RemoteException{
a;
}
public BB
return
getRef_B() throws
RemoteException{
b;
}
public CC getRef_C() throws
return
RemoteException{
c;
}
}
Bc 6: Xy dng chng trnh pha server. Chng trnh ny phi thc hin cc nhim v
sau(nh k thut c bn):
To i tng FFImpl
java.rmi.*;
import
java.rmi.server.*;
class
FFServer{
Exception
{
FF
f=new
FFImpl();
UnicastRemoteObject.exportObject(f);
Naming.bind(rmi://localhost/ffObj,f);
System.out.println(Server da san sang...);
IT
}}
PT
//FFClient.java
import
class
java.rmi.*;
FFClient{
f=(FF)Naming.lookup(rmi://localhost/ffObj);
a=f.getRef_A();
BB
b=f.getRef_B();
CC
c=f.getRef_C();
}}
*.java
AAImpl
D:\RMI\Factory>rmic
BBImpl
D:\RMI\Factory>rmic
CCImpl
D:\RMI\Factory>rmic
FFImpl
IT
PT
D:\RMI\Factory>java FFClient
Lu : Nu chy chng trnh server v client trn 2 my tnh ni mng th phi phn b cc tp
server v cc tp pha client tng t nh k thut c bn nhng nhiu i tng. V phi i a
ch trong chui URL pha chng trnh client l a ch ca server(trong lookup()).
VI. CASE STUDY 1: LOGIN T XA DNG RMI
1. Bi ton
Chng trnh pha client phi hin giao din ha, trong c mt text nhp
username, mt text nhp password, v mt nt nhn Login.
Khi nt Login c click, chng trnh client s triu gi lm kim tra login t server
RMI, ly thng tin ng nhp (username/password) trn form giao din kim tra
Sau khi c kt qu kim tra (ng nhp ng, hoc sai), client s hin th thng bo
tng ng vi kt qu nhn c: nu ng nhp ng th thng bo login thnh cng.
Nu ng nhp sai th thng bo l username/password khng ng.
Yu cu kin trc h thng c hai pha client v server RMI u c thit k theo
m hnh MVC
2. Thit k h thng
V h thng c thit k theo m hnh client/server RMI nn mi pha client, server s c mt
s lp ring, cc s ny c thit k theo m hnh MVC.
2.1 S lp pha client
S lp ca pha client c thit k theo m hnh MVC trong Hnh 5.6, bao gm 3 lp chnh
tng ng vi s M-V-C nh sau:
Lp User: l lp tng ng vi thnh phn model (M), bao gm hai thuc tnh
username v password, cc hm khi to v cc cp getter/setter tng ng vi cc
thuc tnh.
PT
IT
IT
PT
S lp ca pha server c thit k theo m hnh MVC trong Hnh 5.7, bao gm 3 lp chnh
tng ng vi s M-V-C nh sau:
-
Giao din RMILoginInterface: l giao din (interface) khai bo i tng t xa, trong
n khai bo th tc checkLogin(): th tc nhn vo mt tham s kiu User, tr kt
qu v dng String.
PT
IT
public User(){
}
IT
PT
Lp RMILoginClientView.java
package rmi.client;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import
import
import
import
import
import
import
import
java.awt.event.WindowEvent;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JOptionPane;
javax.swing.JPanel;
javax.swing.JPasswordField;
javax.swing.JTextField;
IT
PT
this.setContentPane(content);
this.pack();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Lp RMILoginClientControl.java
package rmi.client;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import rmi.server.RMILoginInterface;
public class RMILoginClientControl {
private RMILoginClientView view;
private String serverHost = "localhost";
private int serverPort = 3232;
private RMILoginInterface rmiServer;
private Registry registry;
private String rmiService = "rmiLoginServer";
try{
IT
PT
Lp ClientRun.java
package rmi.client;
public class ClientRun {
public static void main(String[] args) {
RMILoginClientView view
= new RMILoginClientView();
RMILoginClientControl control = new RMILoginClientControl(view);
view.setVisible(true);
}
}
PT
Interface RMILoginInterface.java
IT
package rmi.server;
import java.rmi.Remote;
import java.rmi.RemoteException;
import rmi.client.User;
Lp RMILoginServerControl.java
package rmi.server;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import rmi.client.User;
public class RMILoginServerControl extends UnicastRemoteObject implements
RMILoginInterface{
private
private
private
private
private
IT
PT
Lp ServerRun.java
package rmi.server;
public class ServerRun {
public static void main(String[] args) {
RMILoginServerView view
= new RMILoginServerView();
try{
RMILoginServerControl
control = new RMILoginServerControl(view);
}catch(Exception e){
e.printStackTrace();
}
}
}
PT
IT
4. Kt qu
Login li:
Chng trnh pha client TCP phi hin giao din ha, trong c mt text
nhp username, mt text nhp password, v mt nt nhn Login.
Ti pha server TCP, khi nhn c yu cu kim tra ang nhp (km theo
username/password), n s triu gi hm kim tra ng nhp t xa ca RMI
Sau khi c kt qu kim tra (ng nhp ng, hoc sai), server TCP s gi li cho
client TCP.
Yu cu kin trc h thng c hai pha client TCP, server TCP v server RMI u
c thit k theo m hnh MVC
PT
2. Thit k h thng
IT
H thng s bao gm ba pha: client TCP, server TCP, v server RMI. Mi pha u c thit k
theo m hnh MVC.
2.1 S lp pha client TCP
IT
PT
S lp ca pha client c thit k theo m hnh MVC trong Hnh 5.9, bao gm 3 lp chnh
tng ng vi s M-V-C nh sau:
-
Lp User: l lp tng ng vi thnh phn model (M), bao gm hai thuc tnh
username v password, cc hm khi to v cc cp getter/setter tng ng vi cc
thuc tnh.
PT
IT
S lp ca pha server c thit k theo m hnh MVC trong Hnh 5.11, bao gm 3 lp chnh
tng ng vi s M-V-C nh sau:
-
Giao din RMILoginInterface: l giao din (interface) khai bo i tng t xa, trong
n khai bo th tc checkLogin(): th tc nhn vo mt tham s kiu User, tr kt
qu v dng String.
PT
IT
IT
Lp User.java
PT
public User(){
}
Lp ClientView.java
package rmi_tcp.tcpClient;
import
import
import
import
import
import
import
import
import
import
import
import
java.awt.FlowLayout;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
javax.swing.JButton;
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JOptionPane;
javax.swing.JPanel;
javax.swing.JPasswordField;
javax.swing.JTextField;
IT
PT
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e) {
}
public User getUser(){
User model = new User(txtUsername.getText(), txtPassword.getText());
return model;
}
public void showMessage(String msg){
JOptionPane.showMessageDialog(this, msg);
}
public void addLoginListener(ActionListener log) {
btnLogin.addActionListener(log);
}
}
Lp ClientControl.java
package rmi_tcp.tcpClient;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ClientControl {
private ClientView view;
private String serverHost = "localhost";
private int serverPort = 8888;
IT
PT
}
}
}
Lp ClientRun.java
package rmi_tcp.tcpClient;
public class ClientRun {
public static void main(String[] args) {
ClientView view = new ClientView();
Lp ServerControl.java
IT
PT
package rmi_tcp.tcpServer;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import rmi_tcp.rmiServer.RMILoginInterface;
import rmi_tcp.tcpClient.User;
}
private void openServer(int portNumber){
try {
myServer = new ServerSocket(portNumber);
}catch(IOException e) {
view.showMessage(e.toString());
e.printStackTrace();
}
}
IT
PT
}
}
Lp ServerRun.java
package rmi_tcp.tcpServer;
public class ServerRun {
public static void main(String[] args) {
ServerView view
= new ServerView();
Interface RMILoginInterface.java
package rmi_tcp.rmiServer;
import java.rmi.Remote;
import java.rmi.RemoteException;
import rmi_tcp.tcpClient.User;
IT
PT
Lp RMILoginServerControl.java
package rmi_tcp.rmiServer;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import rmi.client.User;
this.view = view;
getDBConnection("usermanagement", "root", "12345678");
view.showMessage("RMI server is running...");
// dang ki RMI server
try{
registry = LocateRegistry.createRegistry(serverPort);
registry.rebind(rmiService, this);
}catch(RemoteException e){
throw e;
}
}
public String checkLogin(User user) throws RemoteException{
String result = "";
if(checkUser(user))
result = "ok";
return result;
}
IT
PT
try {
Class.forName(dbClass);
con = DriverManager.getConnection (dbUrl, username, password);
}catch(Exception e) {
view.showMessage(e.getStackTrace().toString());
}
Lp ServerRun.java
package rmi_tcp.rmiServer;
Login li:
PT
IT
4. Kt qu
VIII. KT LUN
Qua cc mc ca chng ny, chng ta lm sng t k thut lp trnh, c ch truyn thng v
bn cht ca lp trnh phn tn i tng ca RMI. Thng qua , sinh vin c th hiu oc cc
k thut lp trnh khc nh RPC, DCOM, CORBA, EJB, WebService... vi cc k thut lp trnh
OOP, SOP v kin trc nhiu tng. Ngoi cc vn nu trong chng, cn mt s k thut khc
ca RMI khng km phn quan trng m s c cp n trong bi ging v thng qua bi tp
ca sinh vin nh: Vn nh ngha b ng k, vn tun t ho i tng, K thut gi i
PT
IT
tng t xa bng phng thc ng, k thut kch hot i tng t xa t ng, chnh sch bo
mt t pha client.v.v..
PHN IV.
LP TRNH TRUYN THNG QUA MNG PSTN&ET
CHNG 5
LP TRNH NG DNG TRUYN THNG
QUA MNG IN THOI CNG CNG (PSTN)
PT
IT
PT
IT
CallControlCall
CallControlCallObserver
CallControlConnection
CallControlTerminal
CallControlTerminalConnection
CallControlTerminalObserver
Gi callcenter
Gi javax.telephony.callcenter cung cp kh nng thc hin qun l cc trung tm cuc
gi ln mc cao. V d nh: nh tuyn, phn b cuc gi t ng ACD, d bo cuc gi v
lin kt d liu ng dng vi i tng in thoi. Gi ny gm cc lp sau:
ACDAddress
ACDAddressObserver
ACDConnection
ACDManagerAddress
ACDManagerConnection
AgentTerminal
AgentTerminalObserver
CallCenterAddress
CallCenterCall
CallCenterCallObserver
CallCenterProvider
RouteAddress
RouteCallback
RouteSession
Gi Media.
Gi javax.telephony.media cho php truy nhp ti cc lung(stream) phng tin truyn
thng lin quan n cuc gi. Chng cho php c v vit d liu t nhng lung phng
tin truyn thng ny. Gi ny gm cc lp:
MediaCallObserver
MediaTerminalConnection
Gi Phone:
Gi javax.telephony.phone cho php cc ng dng iu khin cc c tnh vt l ca
phn cng in thoi.
Gi Phone gm cc lp:
Component
ComponentGroup
PhoneButton
PhoneDisplay
PhoneGraphicDisplay
PhoneHookswitch
PhoneLamp
PT
IT
PhoneMicrophone
PhoneRinger
PhoneSpeaker
PhoneTerminal
PhoneTerminalObserver
Gi capabilities :
Gi javax. telephony.capabilities l gi cung cp cho cc ng dng kh nng truy vn ti
hot ng xc nh mt khi n c thc hin. V n gm cc lp sau :
AddressCapabilities
CallCapabilities
ConnectionCapabilities
ProviderCapabilities
TerminalCapabilities
TerminalConnectionCapabilities
Gi Private Data
Gi javax.telephony.privatedata cho php cc ng dng truyn trc tip d liu trn cc
chuyn mch cng. D liu ny c s dng ch dn chuyn mch thc hin mt thao
tc chuyn mch c.
2. C s ca JTAPI.
Mc ch ca th vin JTAPI c xy dng to ra mt giao din cho php trnh ng dng
Java giao tip vi h thng in thoi. im giao tip ny xc nh mc iu khin m mt
ng dng phi c. JTAPI h tr c 2 kiu ng dng: first-party v third-party.
Trong ng dng first- party, giao din c nh v ti thit b u cui. ng dng c cng mc
iu khin nh cuc gi in thoi bnh thng ca ngi dng. Trong kch bn iu khin
third party, giao din c xc nh bn trong h thng in thoi v ph thuc vo h thng
in thoi. S truy cp bn trong ny thng cung cp cho ng dng nhiu kh nng iu khin
hn kch bn first- party.
PT
IT
PT
IT
IT
vi hai ngi tham gia. M hnh n gin thm mt thnh vin th ba vi cc i tng kt ni,
a ch, kt ni u cui v thit b u cui cho ngi th ba tham gia.
PT
PT
IT
i tng Call: i tng ny th hin mt cuc gi in thoi l lung thng tin gia
ngi cung cp dch v v cc thnh vin ca cuc gi. Mt cuc gi in thoi bao gm
mt i tng Call v khng hoc nhiu kt ni. Trong kiu gi two-party gm mt i
tng Call v 2 kt ni, cn trong kiu hi tho th c 3 hoc nhiu hn s kt ni vi mt
i tng Call.
i tng Address: i tng ny biu din mt s in thoi. N l s tru tng i
vi mt im cui logic ca mt cuc gi in thoi. Trong thc t mt s in thoi c
th tng ng vi mt s im cui vt l.
i tng Connection: Mt i tng Connection m hnh ho lin kt truyn thng
gia i tng Call v i tng Address. i tng Connection c th trong mt trong
cc trng thi khc nhau ch th trng thi quan h hin thi gia Call v Address.
IT
PT
4.3. Cc ph ng th c gi c t li JTAPI
Gi c t li c a JTAPI nh ngha 3 ph
ng th c h tr cc c tr ng c b n: Thi t t
m t cu c g i, tr l i cu c g i v hu k t n i c a m t cu c g i. Cc ph
ng th c
t
ng ng v i cc tc v ny l Call.connect(), TerminalConnection.answer(),
Connection.disconnect().
Ph ng th c Call.connect():Khi m t ng d ng c i t
ng r i( thu
c thng qua
ph
ng th c Provider.createCall()), n c th thi t l p m t cu c g i i n tho i
b ng cch s d ng ph
ng th c Call.connect(). ng d ng ph i ch ra ddoois t
ng
Terminal ngu n( i m cu i v t l) v i t
ng Address ngu n( i m cu i logic) trn
Terminal . N cng cung c p m t chu i s i n tho i ch. Hai i t
ng
Connection
c tr v t ph
ng th c Call.connect() bi u di n cc u cu i
ngu n v ch c a m t cu c g i i n tho i.
TerminalConnection.answer(): Khi m t cu c g i i t i m t Terminal, n s
c ch
th b i i t
ng TerminalConnection i v i Terminal trong tr ng thi RINGING.
T i th i i m , ng d ng s g i ph
ng th c TerminalConnection.answer()
tr l i cu c g i t i .
Connection.disconnect(): Ph
ng th c ny
c g i lo i b Address t m t cu c
tho i. i t
ng Connection bi u di n quan h i t
ng Address v i cu c g i
i n tho i. ng d ng s g i ph
ng th c ny khi i t
ng Connection ang
tr ng thi CONNECTED v tr v k t qu l i t
ng Connetction chuy n n
tr ng thi DISCONNECTED.
PT
IT
c bi u di n nh
PT
IT
Hnh 6.9. L
c d ch chuy n tr ng thi c a Connection
4.4.3. Cc tr ng thi i t ng TerminalConnection
L
c d ch chuy n tr ng thi c a i t
ng TerminalConnection th hi n nh hnh 6.10.
PT
IT
Hnh 6.10. L
c d ch chuy n tr ng thi c a TerminalConnection
4.5. Thi t t m t cu c g i i n tho i
Ph n ny s m t s thay i tr ng thi c a ton b m hnh g i ph i tr i qua khi thi t t
m t cu c g i i n tho i n gi n. Qu trnh ny c th
c th hi n b ng m t l
c
nh th i m hnh g i nh hnh 6.11.
Hnh 6.11. L
c nh th i m hnh cu c g i
Trong l
c trn, cc b
c th i gian r i r c b i cc s nguyn h
ng xu ng theo tr c tung.
L
c ny bi u di n m t cu c g i n gi n ki u two-party. L
c ny chia lm 2
ph n, n a tri v n a ph i. N a tri bi u di n i m cu i ngu n c a cu c g i v n a
ph i bi u di n i m cu i ch c a cu c g i.
II. CU HNH H THNG
PT
IT
JTAPI chy trn nhiu cu hnh h thng khc nhau, bao gm trung tm phc v v my tnh
mng t xa truy nhp ti nguyn in thoi qua mng. Trong cu hnh u tin, mt my tnh
mng ang chy ng dng JTAPI v ang truy nhp nhng ti nguyn in thoi qua mt mng
c minh ha trong hnh 6.12. Cu hnh th hai ng dng ang chy trn mt my tnh vi
nhng ti nguyn in thoi ring c minh ha trong hnh 6.13.
1. Cu hnh my tnh mng
Trong cu hnh ny, ng dng JTAPI hay Java applet chy trn mt trm t xa. Trm lm vic
ny c th l mt my tnh ni mng. N truy nhp ti nguyn mng, s dng mt trung tm
qun l k thut in thoi. JTAPI giao tip vi b phn phc v ny qua mt c ch truyn
thng t xa, nh RMI ca Java, JOE hay mt giao thc in thoi no . Cu hnh ny wcj
th hin nh hnh 6.10.
2. Cu hnh desktop
Trong cu hnh my bn, ng dng JTAPI hay Java applet chy trn cng trm lm vic.
Cu hnh desktop th hin nh hnh 6.13.
PT
IT
}
}
}
}
PT
IT
import MyOutCallObserver;
public class Outcall {
public static final void main(String args[]) {
/*
* Create a provider by first obtaining the default implementation of
* JTAPI and then the default provider of that implementation.
*/
Provider myprovider = null;
try {
JtapiPeer peer = JtapiPeerFactory.getJtapiPeer(null);
myprovider = peer.getProvider(null);
} catch (Exception excp) {
System.out.println("Can't get Provider: " + excp.toString());
System.exit(0);
}
/*
* We need to get the appropriate objects associated with the
* originating side of the telephone call. We ask the Address for a list
* of Terminals on it and arbitrarily choose one.
*/
Address origaddr = null;
Terminal origterm = null;
try {
origaddr = myprovider.getAddress("4761111");
/* Just get some Terminal on this Address */
Terminal[] terminals = origaddr.getTerminals();
if (terminals == null) {
System.out.println("No Terminals on Address.");
System.exit(0);
}
origterm = terminals[0];
} catch (Exception excp) {
// Handle exceptions;
}
/*
* Create the telephone call object and add an observer.
*/
Call mycall = null;
try {
mycall = myprovider.createCall();
mycall.addObserver(new MyOutCallObserver());
} catch (Exception excp) {
// Handle exceptions
}
/*
* Place the telephone call.
*/
try {
Connection c[] = mycall.connect(origterm, origaddr, "5551212");
} catch (Exception excp) {
IT
PT
try {
TermConnEv tcev = (TermConnEv)evlist[i];
Terminal term = termconn.getTerminal();
termconn = tcev.getTerminalConnection();
name = term.getName();
} catch (Exception excp) {
// Handle exceptions.
}
String msg = "TerminalConnection to Terminal: " + name + " is ";
if (evlist[i].getID() == TermConnActiveEv.ID) {
System.out.println(msg + "ACTIVE");
}
else if (evlist[i].getID() == TermConnRingingEv.ID) {
System.out.println(msg + "RINGING");
/* Answer the telephone Call using "inner class" thread */
try {
final TerminalConnection _tc = termconn;
Runnable r = new Runnable() {
public void run(){
try{
_tc.answer();
} catch (Exception excp){
// handle answer exceptions
}
};
};
Thread T = new Thread(r);
T.start();
} catch (Exception excp) {
// Handle Exceptions;
}
} else if (evlist[i].getID() == TermConnDroppedEv.ID) {
System.out.println(msg + "DROPPED");
}
}
}
IT
}
}
import javax.telephony.*;
import javax.telephony.events.*;
import MyInCallObserver;
PT
/*
* Create a provider and monitor a particular terminal for an incoming call.
*/
public class Incall {
public static final void main(String args[]) {
/*
* Create a provider by first obtaining the default implementation of
* JTAPI and then the default provider of that implementation.
*/
Provider myprovider = null;
try {
JtapiPeer peer = JtapiPeerFactory.getJtapiPeer(null);
myprovider = peer.getProvider(null);
} catch (Exception excp) {
System.out.println("Can't get Provider: " + excp.toString());
System.exit(0);
}
/*
* Get the terminal we wish to monitor and add a call observer to that
* Terminal. This will place a call observer on all call which come to
* that terminal. We are assuming that Terminals are named after some
* primary telephone number on them.
*/
try {
Terminal terminal = myprovider.getTerminal("4761111");
terminal.addCallObserver(new MyInCallObserver());
} catch (Exception excp) {
System.out.println("Can't get Terminal: " + excp.toString());
System.exit(0);
}
}
}
PT
IT
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import com.jpackages.jdun.*;
import javax.swing.border.*;
public class Do_an extends JFrame {
public class DialNotify implements DialingNotification {
// Phuong thuc goi lai
public void notifyDialingState(String name, int state, int error) {
// Hien thi y nghia cua trang thai quay so moi
System.out.println("Tien trinh - " + name + ": (" + state + ") " +
DialingState.getDialingStateString(state));
// Neu co loi thi hien thi y nghia cua ma loi
if (error != 0) {
System.out.println("Loi:"+error+""+
dum.getErrorMessageForCode(error));
}
}
}
// handle cho minh hoa ve quan ly quay so (DialUpManager)
DialUpManager dum;
// Minh hoa lop DialNotify (da dinh nghia o tren) ma co phuong thuc goi lai
DialNotify dnot = new DialNotify();
// Dinh nghia giao dien do hoa
JPanel contentPane;
BorderLayout borderLayout1 = new BorderLayout();
JPanel jPanel1 = new JPanel();
JPanel jPanel2 = new JPanel();
JScrollPane jScrollPane1 = new JScrollPane();
DefaultListModel lm = new DefaultListModel();
JList jList1 = new JList(lm);
JPanel jPanel3 = new JPanel();
BorderLayout borderLayout2 = new BorderLayout();
JButton jButtonConnect = new JButton();
JButton jButtonDisconnect = new JButton();
BorderLayout borderLayout3 = new BorderLayout();
JPanel jPanel4 = new JPanel();
JLabel jLabel1 = new JLabel();
JButton jButtonRefresh = new JButton();
JPanel jPanel5 = new JPanel();
FlowLayout flowLayout1 = new FlowLayout();
JButton jButtonDelete = new JButton();
JButton jButtonRename = new JButton();
JPanel jPanel6 = new JPanel();
PT
IT
PT
IT
}
// Danh sach JList
public void refreshList() {
lm.clear();
try {
// Tim nap ten
String[] names = dum.getEntryNames();
for (int i=0; i < names.length; i++) {
lm.addElement(names[i]);
}
this.jList1.repaint();
}
catch (Exception e) {}
}
//Khoi tao cac thanh phan
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(borderLayout1);
this.setSize(new Dimension(500, 400));
this.setTitle("Chuong trinh minh hoa JDUNPhamHienTN2008@yahoo.com");
jPanel1.setLayout(borderLayout2);
jScrollPane1.setPreferredSize(new Dimension(660, 80));
jPanel1.setPreferredSize(new Dimension(260, 100));
jButtonConnect.setPreferredSize(new Dimension(105, 24));
jButtonConnect.setText("Ket noi");
jButtonConnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jButtonConnect_actionPerformed(e);
}
});
jButtonDisconnect.setPreferredSize(new Dimension(105, 24));
jButtonDisconnect.setText("Ngat ket noi");
jButtonDisconnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jButtonDisconnect_actionPerformed(e);
}
});
jPanel2.setLayout(borderLayout3);
jLabel1.setText("Nhap ten quay so");
jButtonRefresh.setPreferredSize(new Dimension(79, 24));
jButtonRefresh.setText("Lam lai");
jButtonRefresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jButtonRefresh_actionPerformed(e);
}
});
PT
IT
jRadioButtonDefault.addActionListener(new
java.awt.event.ActionListener()
PT
IT
PT
IT
// Cap nhat danh sach(JList) sau khi doi tuong da duoc xoa
this.refreshList();
PT
IT
}
// Doi ten doi tuong duoc chon
void jButtonRename_actionPerformed(ActionEvent e) {
String entryName = (String) this.jList1.getSelectedValue();
if (entryName == null)
return;
// Doi ten moi
String message = "Nhap ten moi '" + entryName + "'";
String newname = (String) JOptionPane.showInputDialog(this, message, "Doi
ten", JOptionPane.PLAIN_MESSAGE, null, null, entryName);
if (newname == null)
return;
if (newname.equals(entryName))
return;
// DOi ten bat ky doi tuong nao sang ten moi
dum.renameEntry(entryName, newname);
// Cap nhat lai danh sac (JList) sau khi doi tuong duoc chon da duoc doi
ten
this.refreshList();
}
void jCheckBox1_actionPerformed(ActionEvent e) {
if (jCheckBox1.isSelected())
this.enableParams(true);
else
this.enableParams(false);
}
// Khi mot danh sach cac lua chon duoc tao ra thi nap username/password
thich hop.
void jList1_valueChanged(ListSelectionEvent e) {
String entryName = (String) this.jList1.getSelectedValue();
if (entryName == null)
return;
// Tim nap username/password
String password = dum.getPassword(entryName);
String username = dum.getUsername(entryName);
// Hien thi username/password
this.jTextFieldUsername.setText(username);
this.jPasswordField1.setText(password);
// Tim nap cac thuoc tinh doi tuong
DialUpEntryProperties props = dum.getDialUpEntryProperties(entryName);
// Hien thi so dien thoai
if (props.getUseCountryAndAreaCodes()) {
String areacode = props.getAreaCode();
String phonenum = props.getLocalPhoneNumber();
this.jTextFieldPhoneNumber.setText(areacode + phonenum);
}
else {
this.jTextFieldPhoneNumber.setText(props.getLocalPhoneNumber());
PT
IT
}
}
void phoneButtonChange() {
if (this.jRadioButtonDefault.isSelected()) {
this.jTextFieldPhoneNumber.setEditable(false);
}
else {
this.jTextFieldPhoneNumber.setEditable(true);
}
}
void jRadioButtonDefault_actionPerformed(ActionEvent e) {
phoneButtonChange();
}
void jRadioButtonOverride_actionPerformed(ActionEvent e) {
phoneButtonChange();
}
//Phuong thuc chinh
public static void main(String[] args) {
Do_an frame = new Do_an();
//Can giua cho cua so
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation((screenSize.width
-frameSize.width)
/
(screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
}
}
2,
V. KT LUN
Trong chng nay chng ta kho st gi th vin JTAPI v k thut lp trnh vi n. Qua
chng ny sinh vin nm c cu trc ca th vin JTAPI, cc khi nim, m hnh v cch ci
t chng trnh vi cc cuc gi in thoi n gin. Trn c s sinh vin c th pht trin
cc chng trnh ng dng thc t nh dch v truy cp t xa RAS, hi tho trc tuyn v cc
cng ngh lin qua n IP khc, nht l cc dch v trn h thng in thoi doanh nghip(ET:
Enterprise Telephony).
IT
thng tin/d liu trn mi trng mng Internet khng an ton thng c bo
m bi c ch bo mt thc hin trn tng vn ti c tn Lp cng bo mt SSL
(Secure Socket Layer) - mt gii php k thut hin nay c s dng kh ph bin
trong cc h iu hnh mng my tnh trn Internet. Giao thc SSL c hnh
thnh v pht trin u tin nm 1994 bi nhm nghin cu Netscape dn dt bi
PT
Elgammal, v ngy nay tr thnh chun bo mt thc hnh trn mng Internet.
Phin bn SSL hin nay l 3.0 v vn ang tip tc c b sung v hon thin.
Tng t nh SSL, mt giao thc khc c tn l Cng ngh truyn thng ring t
PCT (Private Communication Technology) c xng bi Microsoft, hin nay
cng c s dng rng ri trong cc mng my tnh chy trn h iu hnh
Windows NT. Ngoi ra, mt chun ca Nhm c trch k thut Internet IETF
(Internet Engineering Task Force) c tn l Bo mt lp giao vn TLS (Transport
Layer Security) da trn SSL cng c hnh thnh v xut bn di khun kh
nghin cu ca IETF Internet Draft c tch hp v h tr trong sn phm ca
Netscape.
2. Kha Key
nh ngha kha
Kha (key) l mt thng tin quan trng dng m ha thng tin hoc gii m
thng tin b m ha. C th hiu nm na kha ging nh l mt khu(password).
di kha c tnh theo bit: 128 bits, 1024 bits hay 2048 bits,...
Kha cng di th cng kh ph. Chng hn nh kha RSA 1024 bits
ng ngha vi vic chn 1 trong 21024 kh nng.
Password v PassParse
IT
3. Thut ton m ha
PT
PT
IT
Khi ngi A mun gi thng ip cho ngi B th ngi B cn bit kha chung
ca ngi A. (Kha ny c ngi A cng b cng khai). Ngi B m ha cc
thng tin gi n ngi A bng kha chung ca ngi A. Ch c ngi A mi c
kha ring gii m cc thng tin ny. Nh nh thng tin ny c ri vo tay
ngi khc th h cng khng th gii m c v ch c ngi A mi c kha
ring dnh cho vic gii m ng thng ip trn.
PT
IT
IT
nhn dng/kho theo phin" (session ID, session key) duy nht cho ln lm vic
. Sau ng dng khch (trnh duyt) yu cu c chng ch in t (digital
certificate) xc thc ca ng dng ch (web server).
PT
IT
da trn phng php "tn cng vt cn" (brute-force attack) bng cch th-sai
min khng gian cc gi tr c th ca kho. S php th-sai tng ln khi di
kho tng v dn n vt qu kh nng v cng sut tnh ton, k c cc siu my
PT
IT
PT
Gi javax.net.ssl (JSSE)
Gi javax.rmi.ssl (SSL/TLS-based RMI Socket Factories)
1.1. Lp SSL
IT
PT
PT
IT
SSLServerSocketFactory sslserversocketfactory =
(SSLServerSocketFactory)
SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket =
(SSLServerSocket)
sslserversocketfactory.createServerSocket(9999);
SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
InputStream inputstream = sslsocket.getInputStream();
InputStreamReader
inputstreamreader
=
new
InputStreamReader(inputstream);
BufferedReader
bufferedreader
=
new
BufferedReader(inputstreamreader);
String string = null;
while ((string = bufferedreader.readLine()) != null) {
System.out.println(string);
System.out.flush();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
}
Client source code (EchoClient.java)
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import java.io.*;
public class EchoClient {
public
static
void
main(String[] arstring) {
try {
SSLSocketFactory
sslsocketfactory
=
(SSLSocketFactory)
SSLSocketFactory.getDefault();
SSLSocket
sslsocket
=
(SSLSocket)
sslsocketfactory.createSocket("localhost", 9999);
InputStream inputstream = System.in;
InputStreamReader
inputstreamreader
=
new
InputStreamReader(inputstream);
BufferedReader
bufferedreader
=
new
BufferedReader(inputstreamreader);
OutputStream outputstream = sslsocket.getOutputStream();
OutputStreamWriter
outputstreamwriter
=
new
OutputStreamWriter(outputstream);
BufferedWriter
bufferedwriter
=
new
BufferedWriter(outputstreamwriter);
String string = null;
while ((string = bufferedreader.readLine()) != null) {
bufferedwriter.write(string + '\n');
bufferedwriter.flush();
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
PT
IT
Gii thch:
-genkey: Lnh to key
-keystore mySrvKeystore: Tn key l mySrvKeystore
-keyalg RSA: Thut ton dng m ha l RSA
V phn ng dng qua giao din dng lnh th s dng chng trnh mu
ging nh trn. Chy nh sau:
To chng nhn:
keytool -genkey -keystore mySrvKeystore -keyalg RSA
Mt khu s in l 123456
Sau khi to xong chng ch th copy file key vo trong th mc cha file
Pha server th chng ch c lu trong keyStore
Chy chng trnh:
java
-Djavax.net.ssl.keyStore=mySrvKeystore
Djavax.net.ssl.keyStorePassword=123456 EchoServer
III. KT LUN
Chng ny bc u cp n vn lp trnh mng an ton bo mt m ch
yu vi SSL, l giao thc c s dng rng ri nht cho vic ci t m ho trong
PT
IT
Web. Vi cch tip cn ny, sinh vin c th t nghin cu khai thc cc k thut
lp trnh mng an ton bo mt khc nhau, khai thc cc h tr khc nhau ca cc
mi trng Java, .NET...(bo mt trong java, phng thc SOCKS, JCA, JCE...).
PT
IT
IT
PT