Professional Documents
Culture Documents
Abc1231 0 PDF
Abc1231 0 PDF
3
1.1. M hnh tham kho 7 tng OSI........................................................................................3
1.2. H giao thc TCP/IP........................................................................................................5
1.3. So snh gia hai giao thc TCP v UDP .........................................................................6
1.4. Cng giao thc.................................................................................................................7
1.5. a ch IP, cc a ch IP dnh ring................................................................................7
1.6. a ch tn min: loi A, loi MX.. .................................................................................8
1.7. Mt s giao thc tng ng dng: HTTP, SMTP, POP3, FTP... ...................................8
CHNG 2: LP TRNH MNG TRONG .NET FRAMEWORK ........................................9
2.1. Socket hng kt ni (TCP Socket) ................................................................................9
2.1.1. Gii thiu v NameSpace System.Net v System.Net.Sockets ..............................10
2.1.2. Vit chng trnh cho pha my ch.......................................................................11
2.1.3. Vit chng trnh cho pha my khch...................................................................13
2.1.4. S dng cc lung nhp xut vi Socket................................................................14
2.2. Socket khng hng kt ni (UDP Socket)...................................................................17
2.2.1. Vit chng trnh cho pha my ch.......................................................................17
2.2.2. Vit chng trnh cho pha my khch...................................................................18
2.2.3. S dng lp System.IO.MemoryStream to vng m nhp xut.....................20
2.3. S dng cc lp h tr c xy dng t lp Soket .....................................................20
2.3.1. Lp TCPClient........................................................................................................21
2.3.2. Lp TCPListener ....................................................................................................22
2.3.3. Lp UDPClient .......................................................................................................24
2.4. Socket khng ng b....................................................................................................26
2.4.1. M hnh x l s kin ca windows .......................................................................26
2.4.2. S dng Socket khng ng b ..............................................................................27
2.4.3. V d v Socket khng ng b..............................................................................28
2.4.4. S dng cc phng thc Non-blocking ................................................................35
2.5. S dng Thread trong cc ng dng mng ....................................................................39
2.5.1. S dng Thread trong chng trnh .Net ................................................................40
2.5.2. S dng Thread trong cc chng trnh Server ......................................................41
2.5.3. S dng Thread gi/nhn d liu.......................................................................41
2.5.4. S dng ThreadPool trong cc chng trnh .Net ..................................................43
2.5.5. S dng ThreadPool trong cc chng trnh Server...............................................47
2.6. K thut IP Multicasting................................................................................................48
2.6.1. Broadcasting l g?..................................................................................................48
2.6.2. S dng Broadcasting gi d liu n nhiu my trong mng cc b ..............48
2.6.3. Multicasting l g? ..................................................................................................49
2.6.4. Socket Multicasting trong .Net ...............................................................................50
2.7 Bi tp p dng ...............................................................................................................53
CHNG 3: XY DNG NG DNG MNG ...................................................................55
3.1. Giao thc ICMP.............................................................................................................55
3.1.1. S dng Raw Socket...............................................................................................55
3.1.2. S dng giao thc ICMP v Raw Socket xy dng chng trnh Ping.............57
3.1.3. S dng giao thc ICMP v Raw Socket xy dng chng trnh TraceRoute .58
3.2. Giao thc SMTP, POP3.................................................................................................60
3.2.1. C bn v h thng Mail v giao thc SMTP, POP3 .............................................60
3.2.2. Ci t SMTP, POP3 Client/Server ........................................................................60
3.3. Giao thc HTTP.............................................................................................................67
3.3.1. C bn v giao thc HTTP .....................................................................................67
3.3.2. Ci t HTTP Client/Server....................................................................................68
3.4. Giao thc FTP................................................................................................................74
3.4.1. C bn v giao thc FTP ........................................................................................74
3.4.2. Ci t FTP Client/Server.......................................................................................84
1
Presentation
(Upper Layer)
Session
Transport Layer
Network Layer
Data Link
Physical
Cc lp trn
3 lp trn cng ca m hnh OSI thng c gi l cc lp ng dng (Application
layers) hay cn gi l cc lp cao. Cc lp ny thng lin quan ti giao tip vi
ngi dng, nh dng ca d liu v phng thc truy nhp cc ng dng .
Hnh 1-2 M t cc lp trn v cung cp thng tin vi cc chc nng ca n qua v
d:
- Lp ng dng: chc nng giao Telnet, HTTP
3
Application
Presentation
Session
Transport Layer
Network Layer
Data Link
Physical
Application layer : y l lp cao nht trong m hnh. N l ni m ngi s
dng hoc kt ni cc chng trnh ng dng vi cc th tc cho php truy nhp vo
mng.
Presentation layer : Lp presentation cung cp cc m v chc nng chuyn
i m c cung cp bi lp ng dng. Cc chc nng m bo rng d liu t
lp ng dng trong mt h thng c th c c bi lp ng dng ca mt h thng
khc. VD : dng m ho d liu t lp ng dng : nh m ho nh jpeg , gif. M
cho php ta c th hin ln trang web .
Session layer : c s dng thit lp, duy tr v kt thc phin lm vic
gia cc lp presentation. Vic trao i thng tin lp ny bao gm yu cu dch v
v p ng yu cu ca cc ng dng trn thit b khc.
Cc lp di.
4 lp di ca m hnh OSI s dng nh ngha lm th no d liu c
truyn i trong cc dy ni vt l, cc thit b mng v i n trm u cui cui cng
l n cc lp ng dng. Qun sch ny ta ch quan tm n 4 lp cui. V s xem xt
tng lp mt cch chi tit giao thip gia cc lp trong m hnh OSI:
S dng phng php protocal stack kt ni gia hai thit b trong mng. Protocal
stack l mt tp hp cc quy nh dng nh ngha lm th no d liu truyn
qua mng.
V d vi : TCP/IP mi Layer cho php d liu truyn qua. Cc lp trao i cc
thng tin cung cp cuc lin lc gia hai thit b trong mng. Cc lp giao tip vi
nhau s dng Protocal Data Unit (PDU). Thng tin iu khin ca PDU c thm
Application
Presentation
Upper Layer Data
Session
TCP Header
Transport
Segment
IP Header
Data
Network
Packet
LLC Header
Data
FCS
Data Link
Frame
MAC Header
Data
FCS
Physical
Bits
0101110101001000010
1.2. H giao thc TCP/IP
Class B
1 0
Class C
1 1 0
Class D
1 1 1 0
Class E
1 1 1 1 0
16
Netid
24
Hostid
Netid
Hostid
Netid
Hostid
Multicast address
Reverved for future use
c im ca Socket hng kt ni
C 1 ng kt ni o gia 2 tin trnh
Mt trong 2 tin trnh phi i tin trnh kia yu cu kt ni.
C th s dng lin lc theo m hnh Client/Server
Trong m hnh Client/Server th Server lng nghe v chp nhn mt yu
cu kt ni
Mi thng ip gi u c xc nhn tr v
Cc gi tin chuyn i tun t
c im ca Socket khng hng kt ni
Hai tin trnh lin lc vi nhau khng kt ni trc tip
Thng ip gi i phi km theo a ch ca ngi nhn
Thng ip c th gi nhiu ln
Ngi gi khng chc chn thng ip ti tay ngi nhn
Thng ip gi sau c th n ch trc thng ip gi trc .
c th thc hin cc cuc giao tip, mt trong hai qu trnh phi cng
b s hiu cng ca socket m mnh s dng.
Mi cng giao tip th hin mt a ch xc nh trong h thng. Khi qu
trnh c gn mt s hiu cng, n c th nhn d liu gi n cng
ny t cc qu trnh khc.
Qu trnh cn li cng yu cu to ra mt socket.
2.1.1. Gii thiu v NameSpace System.Net v System.Net.Sockets
Cung cp mt giao din lp trnh n gin cho rt nhiu cc giao thc mng.
C rt nhiu lp lp trnh
Ta quan tm lp IPAdress, IPEndPoint, DNS,
Lp IPAdress
Mt s Field cn ch :
Any: Cung cp mt a ch IP ch ra rng Server phi lng nghe trn
tt c cc Card mng
Broadcast: Cung cp mt a ch IP qung b
Loopback: Tr v mt a ch IP lp
AdressFamily: Tr v h a ch ca IP hin hnh
Lp IPAddress
Mt s phng thc cn ch :
Phng thc khi to
IPAddress(Byte[])
IPAddress(Int64)
IsLoopback: Cho bit a ch c phi a ch lp khng
Parse: Chuyn IP dng xu v IP chun
ToString: Tr a ch IP v dng xu
TryParse: Kim tra IP dng xu c hp l khng?
Lp IPEndPoint
Mt s phng thc cn ch :
Phng thc khi to
IPEndPoint (Int64, Int32)
IPEndPoint (IPAddress, Int32)
Create: To mt EndPoint t mt a ch Socket
ToString : Tr v a ch IP v s hiu cng theo khun dng aCh:
Cng, v d: 192.168.1.1:8080
Lp DNS
Mt s thnh phn ca lp:
HostName: Cho bit tn ca my c phn gii
GetHostAddress: Tr v tt c IP ca mt trm
GetHostEntry: Gii p tn hoc a ch truyn vo v tr v i tng
IPHostEntry
10
GetHostName: Ly v tn ca my tnh cc b
NameSpace System.Net.Sockets
Mt s lp hay dng: TcpClient, UdpClient, TcpListener, Socket,
NetworkStream,
to ra Socket
Socket(AddressFamily af, SocketType st, ProtocolType pt)
SocketType
Protocoltype
Description
Dgram
Udp
Connectionless communication
Stream
Tcp
Raw
Icmp
Raw
Raw
Connection-oriented
communication
Internet Control Message
Protocol
Plain IP packet communication
using System.Net;
using System.Net.Sockets;
class SockProp {
public static void Main()
{
IPAddress ia = IPAddress.Parse("127.0.0.1");
IPEndPoint ie = new IPEndPoint(ia, 8000);
Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
Console.WriteLine("AddressFamily: {0}", test.AddressFamily);
Console.WriteLine("SocketType: {0}", test.SocketType);
Console.WriteLine("ProtocolType: {0}", test.ProtocolType);
Console.WriteLine("Blocking: {0}", test.Blocking);
test.Blocking = false;
Console.WriteLine("new Blocking: {0}", test.Blocking);
Console.WriteLine("Connected: {0}", test.Connected);
test.Bind(ie);
IPEndPoint iep = (IPEndPoint)test.LocalEndPoint;
Console.WriteLine("Local EndPoint: {0}", iep.ToString());
test.Close();
Console.ReadKey();
}
}
2.1.2. Vit chng trnh cho pha my ch
Vit chng trnh cho pha my ch
To mt Socket
Lin kt vi mt IPEndPoint cc b
Lng nghe kt ni
Chp nhn kt ni
Gi nhn d liu theo giao thc thit k
11
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
class Server{
static void Main(string[] args) {
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
server.Bind(iep);
server.Listen(10);
Console.WriteLine("Cho ket noi tu client");
Socket client = server.Accept();
Console.WriteLine("Chap nhan ket noi tu:{0}",
client.RemoteEndPoint.ToString());
string s = "Chao ban den voi Server";
//Chuyen chuoi s thanh mang byte
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(s);
//gui nhan du lieu theo giao thuc da thiet ke
client.Send(data,data.Length,SocketFlags.None);
while (true) {
data = new byte[1024];
int recv = client.Receive(data);
if (recv == 0) break;
//Chuyen mang byte Data thanh chuoi va in ra man hinh
s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Clien gui len:{0}", s);
//Neu chuoi nhan duoc la Quit thi thoat
if (s.ToUpper().Equals("QUIT")) break;
//Gui tra lai cho client chuoi s
s = s.ToUpper();
data = new byte[1024];
12
data = Encoding.ASCII.GetBytes(s);
client.Send(data, data.Length, SocketFlags.None);
}
client.Shutdown(SocketShutdown.Both);
client.Close();
server.Close();
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
class Client {
static void Main(string[] args) {
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
client.Connect(iep);
byte[] data = new byte[1024];
int recv = client.Receive(data);
string s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Server gui:{0}", s);
string input;
while (true) {
input = Console.ReadLine();
//Chuyen input thanh mang byte gui len cho server
data = new byte[1024];
data = Encoding.ASCII.GetBytes(input);
client.Send(data, data.Length, SocketFlags.None);
if (input.ToUpper().Equals("QUIT")) break;
data = new byte[1024];
recv = client.Receive(data);
13
s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Server gui:{0}", s);
}
client.Disconnect(true);
client.Close();
}
}
Description
CanRead
CanSeek
CanWrite
DataAvailable
class Program {
static void Main(string[] args) {
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2009);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
client.Connect(iep);
NetworkStream ns = new NetworkStream(client);
byte[] data = new byte[1024];
while (true) {
string input = Console.ReadLine();
data = Encoding.ASCII.GetBytes(input);
ns.Write(data, 0, data.Length);
if (input.ToUpper().Equals("QUIT")) break;
data = new byte[1024];
int rec = ns.Read(data, 0, data.Length);
string s = Encoding.ASCII.GetString(data, 0, rec);
Console.WriteLine(s);
}
client.Close();
}
}
Chng trnh Server s dng NetworkStream:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
class Program {
static void Main(string[] args) {
IPEndPoint iep=new IPEndPoint(IPAddress.Parse("127.0.0.1"),2009);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
server.Bind(iep);
server.Listen(10);
Socket client = server.Accept();
byte[] data;
NetworkStream ns = new NetworkStream(client);
while (true) {
data = new byte[1024];
int rec = ns.Read(data, 0, data.Length);
string s = Encoding.ASCII.GetString(data, 0, rec);
Console.WriteLine(s);
data = new byte[1024];
s = s.ToUpper();
if (s.Equals("QUIT")) break;
data = Encoding.ASCII.GetBytes(s);
ns.Write(data, 0, data.Length);
}
15
client.Close();
server.Close();
}
}
Trn c s ca NetworkStream ta c th ni thm cc lung nhp xut theo hng
k t nh StreamReader, StreamWriter
Sau y l mt v d v chng trnh Client/Server s dng lung nhp xut, chng
trnh Server chp php Client gi ln yu cu, nu yu cu l GetDate khng phn bit
ch hoa ch thng th Server tr v cho Client ngy hin ti, nu yu cu l GetTime
khng phan bit hoa thng th Server tr v gi hin ti, nu l Quit th Server ngt
kt ni vi Client, khng phi cc trng hp trn th thng bo khng hiu lnh.
Chng trnh pha Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
class DateTimeClient {
static void Main(string[] args) {
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
client.Connect(iep);
NetworkStream ns = new NetworkStream(client);
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
while (true) {
string input = Console.ReadLine();
sw.WriteLine(input);
sw.Flush();
if (input.ToUpper().Equals("QUIT")) break;
string kq = sr.ReadLine();
Console.WriteLine(kq);
}
sr.Close();
sw.Close();
ns.Close();
client.Close();
}
}
Chng trnh pha Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
16
using System.Net.Sockets;
using System.IO;
class DateTimeServer{
static void Main(string[] args) {
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2009);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
server.Bind(iep);
server.Listen(10);
Socket client = server.Accept();
NetworkStream ns = new NetworkStream(client);
StreamReader sr = new StreamReader(ns
StreamWriter sw = new StreamWriter(ns);
string kq="";
while (true) {
string s = sr.ReadLine();
s=s.ToUpper();
if (s.Equals("QUIT")) break;
if (s.Equals("GETDATE"))
kq = DateTime.Now.ToString("dd/MM/yyyy");
else
if (s.Equals("GETTIME"))
kq = DateTime.Now.ToString("hh:mm:ss");
else
kq = "Khong hieu lenh";
sw.WriteLine(kq);
sw.Flush();
}
sr.Close();
sw.Close();
client.Close();
}
}
2.2. Socket khng hng kt ni (UDP Socket)
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
class Program {
static void Main(string[] args) {
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
server.Bind(iep);
//tao ra mot Endpot tu xa de nhan du lieu ve
IPEndPoint RemoteEp = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote=(EndPoint)RemoteEp;
byte[] data = new byte[1024];
int recv = server.ReceiveFrom(data, ref remote);
string s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("nhan ve tu Client:{0}", s);
data = Encoding.ASCII.GetBytes("Chao client");
server.SendTo(data, remote);
while (true) {
data=new byte[1024];
recv = server.ReceiveFrom(data, ref remote);
s = Encoding.ASCII.GetString(data, 0, recv);
if (s.ToUpper().Equals("QUIT")) break;
Console.WriteLine(s);
data=new byte[1024];
data=Encoding.ASCII.GetBytes(s);
server.SendTo(data,0,data.Length,SocketFlags.None,remote);
}
server.Close();
}
}
2.2.2. Vit chng trnh cho pha my khch
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
class Program {
static void Main(string[] args) {
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
String s = "Chao server";
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(s);
client.SendTo(data, iep);
EndPoint remote = (EndPoint)iep;
18
}
private void btSend_Click(object sender, EventArgs e) {
byte[] data = new byte[1024];
data = Encoding.ASCII.GetBytes(txtSend.Text);
udp1.SendTo(data, ipremote);
}
private void NhanDL() {
while (true) {
byte[] data = new byte[1024];
IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0);
EndPoint remote = (EndPoint)ipe;
int rec = udp1.ReceiveFrom(data, ref remote);
string s = Encoding.ASCII.GetString(data, 0, rec);
txtNoidung.Text += s + "\r\n";
}
}
private void button1_Click(object sender, EventArgs e) {
MessageBox.Show(txtSend.Text.Substring(0, txtSend.Text.IndexOf(" ")));
}
}
2.3.1. Lp TCPClient
Mc ch ca lp UDPClient trn l dng cho lp trnh vi giao thc UDP,
vi giao thc ny th hai bn khng cn phi thit lp kt ni trc khi gi do vy mc
tin cy khng cao. m bo tin cy trong cc ng dng mng, ngi ta cn
dng mt giao thc khc, gi l giao thc c kt ni : TCP (Transport Control
Protocol). Trn Internet ch yu l dng loi giao thc ny, v d nh Telnet, HTTP,
SMTP, POP3 lp trnh theo giao thc TCP, MS.NET cung cp hai lp c tn l
TCPClient v TCPListener.
- Cc thnh phn ca lp TcpClient
+ Phng thc khi to:
Constructor Method
Name
Description
TcpClient ()
TcpClient
(IPEndPoint)
TcpClient
(RemoteHost: String,
Int32)
To mt i tng TcpClient v kt ni n mt my c
a ch v s hiu cng c truyn vo.. RemoteHost c
th l a ch IP chun hoc tn my.
+ Mt s thuc tnh:
Name
Description
Available
Client
Name
Description
Close
Connect
(RemoteHost,
Port)
Kt ni n mt my TCP khc c Tn v
s hiu cng.
21
GetStream
Tr v NetworkStream t gip ta
gi hay nhn d liu. (Thng lm tham
s khi to StreamReader v
StreamWriter) .
Khi gn vo StreamReader v
StreamWriter ri th ta c th gi v nhn
d liu thng qua cc phng thc
Readln, writeline tng ng ca cc lp
ny.
Constructor method
Name
Description
TcpListener (Port:
Int32)
TcpListener
(IPEndPoint)
TcpListener
(IPAddress, Int32)
Name
Description
AcceptSocket
Start
Stop
string s = sr.ReadLine();
s=s.ToUpper();
if (s.Equals("QUIT")) break;
if (s.Equals("GETDATE"))
kq = DateTime.Now.ToString("dd/MM/yyyy");
else
if (s.Equals("GETTIME"))
kq = DateTime.Now.ToString("hh:mm:ss");
else
kq = "Khong hieu lenh";
sw.WriteLine(kq);
sw.Flush();
}
sr.Close();
sw.Close();
client.Close();
}
}
2.3.3. Lp UDPClient
Giao thc UDP (User Datagram Protocol hay User Define Protocol) l mt giao thc
phi kt ni (Connectionless) c ngha l mt bn c th gi d liu cho bn kia m khng cn
bit l bn 9 sn sng hay cha ? (Ni cch khc l khng cn thit lp kt ni gia hai
bn khi tin hnh trao i thng tin). Giao thc ny khng tin cy bng giao thc TCP nhng
tc li nhanh v d ci t. Ngoi ra, vi giao thc UDP ta cn c th gi cc gi tin qung
b (Broadcast) cho ng thi nhiu my.
Trong .NET, lp UDPClient (nm trong System.Net.Sockets) ng gi cc chc nng
ca giao thc UDP.
Constructor methosd
UdpClient ()
UdpClient (AddressFamily)
UdpClient (Int32)
UdpClient (IPEndPoint)
Description
To mt i tng (th hin) mi ca lp
UDPClient.
To mt i tng (th hin) mi ca lp
UDPClient. Thuc mt dng a ch
(AddressFamily) c ch nh.
To mt UdpClient v gn (bind) mt cng cho n.
To mt UdpClient v gn (bind) mt IPEndpoint
(gn a ch IP v cng) cho n.
To mt UdpClient v gn s hiu cng,
AddressFamily
24
PUBLIC Method
Name
Description
BeginReceive
BeginSend
Gi khng ng b d liu ti my xa
Close
ng kt ni.
Connect
EndReceive
EndSend
Receive
Send
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
25
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace UdpChat {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void btSend_Click(object sender, EventArgs e) {
UdpClient send = new UdpClient();
IPEndPoint iepRemote = new IPEndPoint(IPAddress.Parse(txtIp.Text),
int.Parse(txtRemotePort.Text));
byte[] data = new byte[1024];
data = Encoding.UTF8.GetBytes(txtSend.Text);
send.Send(data, data.Length, iepRemote);
txtReceive.Text += "Sender: "+txtSend.Text + "\r\n";
txtSend.Clear();
if (txtSend.Text.ToUpper().Equals("QUIT")) this.Dispose();
}
private void btConnect_Click(object sender, EventArgs e) {
Thread tuyen = new Thread(new ThreadStart(NhanDl));
tuyen.Start();
}
private void NhanDl() {
UdpClient receiver = new UdpClient(int.Parse(txtLocalPort.Text));
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
while (true) {
byte[] data = new byte[1024];
data = receiver.Receive(ref iep);
string s = Encoding.UTF8.GetString(data);
if (s.Trim().ToUpper().Equals("QUIT")) break;
txtReceive.Text += "Receiver: "+ s + "\r\n";
}
}
}
}
2.4. Socket khng ng b
26
Description of Request
Requests Ended BY
BeginAccept()
To accept an incoming
connection
EndAccept()
BeginConnect()
To connect to a remote
host
EndConnect()
BeginReceive()
EndReceive()
BeginReceiveFrom()
EndReceiveFrom()
BeginSend()
EndSend()
BeginSendTo()
To send data to a
specific remote host
EndSendTo()
30
client = (Socket)iar.AsyncState;
try
{
client.EndConnect(iar);
conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
} catch (SocketException)
{
conStatus.Text = "Error connecting";
}
}
void ReceiveData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceive(iar);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
results.Items.Add(stringData);
}
void SendData(IAsyncResult iar)
{
Socket remote = (Socket)iar.AsyncState;
int sent = remote.EndSend(iar);
remote.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), remote);
}
public static void Main()
{
Application.Run(new AsyncTcpClient());
}
}
Chng trnh pha Server:
using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
class AsyncTcpSrvr :Form
{
private TextBox conStatus;
private ListBox results;
private byte[] data = new byte[1024];
private int size = 1024;
private Socket server;
public AsyncTcpSrvr()
{
Text = "Asynchronous TCP Server";
Size = new Size(400, 380);
33
i = 0;
while (true)
{
Console.WriteLine("polling for receive #{0}...", i);
i++;
result = client.Poll(3000000, SelectMode.SelectRead);
if (result)
{
data = new byte[1024];
i = 0;
recv = client.Receive(data);
if (recv == 0)
break;
Console.WriteLine(
Encoding.ASCII.GetString(data, 0, recv));
client.Send(data, recv, 0);
}
}
Console.WriteLine("Disconnected from {0}",
newclient.Address);
client.Close();
newsock.Close();
}
}
Sau y chng ta s vit mt chng trnh Server s dng phng thc Select()
chp nhn 2 kt ni n t client v x l tng kt ni.
Chng trnh Select Server:
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
class SelectTcpSrvr
{
public static void Main()
{
ArrayList sockList = new ArrayList(2);
ArrayList copyList = new ArrayList(2);
Socket main = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
byte[] data = new byte[1024];
string stringData;
37
int recv;
main.Bind(iep);
main.Listen(2);
Console.WriteLine("Waiting for 2 clients...");
Socket client1 = main.Accept();
IPEndPoint iep1 = (IPEndPoint)client1.RemoteEndPoint;
client1.Send(Encoding.ASCII.GetBytes("Welcome to my server"));
Console.WriteLine("Connected to {0}", iep1.ToString());
sockList.Add(client1);
Console.WriteLine("Waiting for 1 more client...");
Socket client2 = main.Accept();
IPEndPoint iep2 = (IPEndPoint)client2.RemoteEndPoint;
client2.Send(Encoding.ASCII.GetBytes("Welcome to my server"));
Console.WriteLine("Connected to {0}", iep2.ToString());
sockList.Add(client2);
main.Close();
while (true)
{
copyList = new ArrayList(sockList);
Console.WriteLine("Monitoring {0} sockets...", copyList.Count);
Socket.Select(copyList, null, null, 10000000);
foreach (Socket client in copyList)
{
data = new byte[1024];
recv = client.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Received: {0}", stringData);
if (recv == 0)
{
iep = (IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Client {0} disconnected.", iep.ToString());
client.Close();
sockList.Remove(client);
if (sockList.Count == 0)
{
Console.WriteLine("Last client disconnected, bye");
return;
}
}
else
client.Send(data, recv, SocketFlags.None);
38
}
}
}
}
Chng trnh Client:
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
class SelectTcpClient
{
public static void Main()
{
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
byte[] data = new byte[1024];
string stringData;
int recv;
sock.Connect(iep);
Console.WriteLine("Connected to server");
recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Received: {0}", stringData);
while (true)
{
stringData = Console.ReadLine();
if (stringData == "exit")
break;
data = Encoding.ASCII.GetBytes(stringData);
sock.Send(data, data.Length, SocketFlags.None);
data = new byte[1024];
recv = sock.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Received: {0}", stringData);
}
sock.Close();
}
}
2.5. S dng Thread trong cc ng dng mng
39
Mt s khi nim
- a nhim (Multitasking): L kh nng h iu hnh lm nhiu cng vic ti mt thi
im
- Tin trnh (Process): Khi chy mt ng dng, h iu hnh s cp pht ring cho ng
dng b nh v cc ti nguyn khc. B nh v ti nguyn vt l ring bit ny
c gi l mt tin trnh. Cc ti nguyn v b nh ca mt tin trnh th ch tin
trnh c php truy cp.
- Tuyn (Thread): Trong h thng, mt tin trnh c th c mt hoc nhiu chui thc
hin tch bit nhau v c th chy ng thi. Mi chui thc hin ny c gi l mt
tuyn (Thread). Trong mt ng dng, Thread khi to u tin gi l Thread s cp
hay Thread chnh.
2.5.1. S dng Thread trong chng trnh .Net
s dng Thread trong .Net ta s dng NameSpace System.Threading
- Mt s phng thc thng dng
Public Method M t
Name
Abort()
Kt thc Thread
Join()
Buc chng trnh phi ch cho thread kt thc (Block) th mi thc hin
tip (cc cu lnh ng sau Join).
Resume()
Sleep()
Start()
Bt u chy (khi ng) mt thread. Sau khi gi phng thc ny, trng
thi ca thread chuyn t trng thi hin hnh sang Running.
Suspend()
M t
CurrentThread
IsAlive
IsBackground
IsThreadPoolThread
Priority
Public Property
Name
M t
ThreadState
- To mt tuyn trong C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
class Program {
static void Main(string[] args) {
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2009);
TcpListener server = new TcpListener(iep);
server.Start();
while (true) {
41
42
using System.Windows.Forms;
class TcpChat:Form
{
private static TextBox newText;
private static ListBox results;
private static Socket client;
private static byte[] data = new byte[1024];
public TcpChat()
{
Text = "TCP Chat Program";
Size = new Size(400, 380);
Label label1 = new Label();
label1.Parent = this;
label1.Text = "Enter text string:";
label1.AutoSize = true;
label1.Location = new Point(10, 30);
newText = new TextBox();
newText.Parent = this;
newText.Size = new Size(200, 2 * Font.Height);
newText.Location = new Point(10, 55);
results = new ListBox();
results.Parent = this;
results.Location = new Point(10, 85);
results.Size = new Size(360, 18 * Font.Height);
Button sendit = new Button();
sendit.Parent = this;
sendit.Text = "Send";
sendit.Location = new Point(220,52);
sendit.Size = new Size(5 * Font.Height, 2 * Font.Height);
sendit.Click += new EventHandler(ButtonSendOnClick);
Button connect = new Button();
connect.Parent = this;
connect.Text = "Connect";
connect.Location = new Point(295, 20);
connect.Size = new Size(6 * Font.Height, 2 * Font.Height);
connect.Click += new EventHandler(ButtonConnectOnClick);
Button listen = new Button();
listen.Parent = this;
listen.Text = "Listen";
listen.Location = new Point(295,52);
listen.Size = new Size(6 * Font.Height, 2 * Font.Height);
listen.Click += new EventHandler(ButtonListenOnClick);
}
void ButtonListenOnClick(object obj, EventArgs ea)
{
results.Items.Add("Listening for a client...");
Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
44
string stringData;
while (true)
{
recv = client.Receive(data);
stringData = Encoding.ASCII.GetString(data, 0, recv);
if (stringData == "bye")
break;
results.Items.Add(stringData);
}
stringData = "bye";
byte[] message = Encoding.ASCII.GetBytes(stringData);
client.Send(message);
client.Close();
results.Items.Add("Connection stopped");
return;
}
public static void Main()
{
Application.Run(new TcpChat());
}
}
2.5.4. S dng ThreadPool trong cc chng trnh .Net
Method
Description
BindHandle()
GetAvailableThreads()
GetMaxThreads()
QueueUserWorkItem()
RegisterWaitForSingleObject()
UnsafeQueueUserWorkItem()
UnsafeRegisterWaitForSingleObject()
using System;
using System.Threading;
class ThreadPoolSample
{
46
47
}
}
class ConnectionThread
{
public TcpListener threadListener;
private static int connections = 0;
public void HandleConnection(object state)
{
int recv;
byte[] data = new byte[1024];
TcpClient client = threadListener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
connections++;
Console.WriteLine("New client accepted: {0} active connections",
connections);
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
while(true)
{
data = new byte[1024];
recv = ns.Read(data, 0, data.Length);
if (recv == 0)
break;
ns.Write(data, 0, recv);
}
ns.Close();
client.Close();
connections;
Console.WriteLine("Client disconnected: {0} active connections",
connections);
}
}
2.6.1. Broadcasting l g?
Broadcast, ting Vit gi l qung b. Trong h thng mng hu tuyn, qung b l
thut ng dng ch vic gi mt gi thng tin n tt cc nt mng trong mng.
thc hin hnh thc qung b, a ch n ca gi tin s l a ch qung b.
C hai loi l: Local Broadcast v Global Broadcast
2.6.2. S dng Broadcasting gi d liu n nhiu my trong mng cc b
Gi gi d liu Broadcast
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class BadBroadcast {
public static void Main() {
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9050);
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
sock.SendTo(data, iep);
sock.Close();
}
48
}
Chng ta phi thit lp nh sau:
class Broadcst {
public static void Main() {
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050);
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050);
string hostname = Dns.GetHostName();
byte[] data = Encoding.ASCII.GetBytes(hostname);
sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.Broadcast, 1);
sock.SendTo(data, iep1);
sock.SendTo(data, iep2);
sock.Close();
}
}
Nhn gi d liu Broadcast
class RecvBroadcst {
public static void Main() {
Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,
ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep); EndPoint ep = (EndPoint)iep;
Console.WriteLine("Ready to receive"); byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
data = new byte[1024]; recv = sock.ReceiveFrom(data, ref ep);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString());
sock.Close();
}
}
2.6.3. Multicasting l g?
Mt a ch multicast cho php thit b gi d liu ti mt tp xc nh trc cc host,
c bit n nh cc nhm multicast, trong cc mng con khc nhau.
Mt s a ch Multicast
a ch multicast Chc nng
224.0.0.0
a ch c s
224.0.0.1
224.0.0.2
49
224.0.0.5
Cc DR trong OSPF
224.0.1.9
Nhm a ch RIPv2
224.0.1.24
+ Central Server
class MultiRecv{
public static void Main() {
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
Console.WriteLine("Ready to receive");
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
EndPoint ep = (EndPoint)iep;
sock.Bind(iep);
sock.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse("224.100.0.1")));
byte[] data = new byte[1024];
int recv = sock.ReceiveFrom(data, ref ep);
string stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString());
sock.Close();
}
}
51
2.7 Bi tp p dng
new MulticastOption(IPAddress.Parse("224.100.0.1")));
receiver = new Thread(new ThreadStart(packetReceive));
receiver.IsBackground = true;
receiver.Start();
}
void ButtonSendOnClick(object obj, EventArgs ea) {
byte[] message = Encoding.ASCII.GetBytes(newText.Text);
newText.Clear();
sock.SendTo(message, SocketFlags.None, multiep);
}
void ButtonCloseOnClick(object obj, EventArgs ea) {
receiver.Abort();
sock.Close();
Close();
}
void packetReceive() {
EndPoint ep = (EndPoint)multiep;
byte[] data = new byte[1024];
string stringData;
int recv;
while (true)
{
recv = sock.ReceiveFrom(data, ref ep);
stringData = Encoding.ASCII.GetString(data, 0, recv);
results.Items.Add("from " + ep.ToString() + ": " + stringData);
}
}
public static void Main() {
Application.Run(new MulticastChat());
}
}
54
new
Socket(AddressFamily.InterNetwork,
SocketType.Raw,
ProtocolType.Icmp);
Raw Socket Format
Value
Description
Ggp
Gateway-to-Gateway Protocol
Icmp
Idp
IDP Protocol
Igmp
IP
A raw IP packet
Ipx
ND
Pup
Raw
A raw IP packet
Spx
SpxII
Unknown
An unknown protocol
Unspecified
An unspecified protocol
Gi gi d liu Raw
ICMP l giao thc khng hng kt ni
S dng phng thc SendTo() ca lp Socket gi
Cng trong giao thc ICMP khng quan trng
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 0);
sock.SendTo(packet, iep);
Nhn gi d liu Raw
S dng phng thc ReceiveForm ca lp Socket
D liu nhn v l mt gi tin IP chng ta phi tch ra ly gi tin ICMP
Raw Socket khng t ng nh dng gi tin ICMP cho chng ta. Chng ta phi t lm
Data Variable
Size
Type
Type
1 byte
Byte
Code
1 byte
Byte
Checksum
2 bytes
multibyte
Byte array
Message
packet.Type = 0x08;
packet.Code = 0x00;
packet.Checksum = 0;
public ICMP(byte[] data, int size) {
Type = data[20];
Code = data[21];
Checksum = BitConverter.ToUInt16(data, 22);
MessageSize = size - 24;
Buffer.BlockCopy(data, 24, Message, 0, MessageSize);
}
public byte[] getBytes() {
byte[] data = new byte[MessageSize + 9];
Buffer.BlockCopy(BitConverter.GetBytes(Type), 0, data, 0, 1);
Buffer.BlockCopy(BitConverter.GetBytes(Code), 0, data, 1, 1);
Buffer.BlockCopy(BitConverter.GetBytes(Checksum), 0, data, 2, 2);
Buffer.BlockCopy(Message, 0, data, 4, MessageSize);
return data;
}
public UInt16 getChecksum() {
UInt32 chcksm = 0;
byte[] data = getBytes();
int packetsize = MessageSize + 8;
int index = 0;
while (index < packetsize) {
chcksm += Convert.ToUInt32(BitConverter.ToUInt16(data, index));
index += 2;
}
chcksm = (chcksm >> 16) + (chcksm & 0xffff);
chcksm += (chcksm >> 16);
return (UInt16)(~chcksm);
}
3.1.2. S dng giao thc ICMP v Raw Socket xy dng chng trnh Ping
57
class Program {
static void Main(string[] args) {
byte[] data = new byte[1024];
int recv;
Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw,
ProtocolType.Icmp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(argv[0]), 0);
EndPoint ep = (EndPoint)iep;
ICMP packet = new ICMP();
packet.Type = 0x08;
packet.Code = 0x00;
packet.Checksum = 0;
Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 0, 2);
Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 2, 2);
data = Encoding.ASCII.GetBytes("test packet");
Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length);
packet.MessageSize = data.Length + 4;
int packetsize = packet.MessageSize + 4;
UInt16 chcksum = packet.getChecksum();
packet.Checksum = chcksum;
host.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 3000);
host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
try {
data = new byte[1024];
recv = host.ReceiveFrom(data, ref ep);
} catch (SocketException) {
Console.WriteLine("No response from remote host");
return;
}
ICMP response = new ICMP(data, recv);
Console.WriteLine("response from: {0}", ep.ToString());
Console.WriteLine(" Type {0}", response.Type);
Console.WriteLine(" Code: {0}", response.Code);
int Identifier = BitConverter.ToInt16(response.Message, 0);
58
3.1.3. S dng giao thc ICMP v Raw Socket xy dng chng trnh
TraceRoute
class TraceRoute {
public static void Main(string[] argv) {
byte[] data = new byte[1024];
int recv, timestart, timestop;
Socket host = new Socket(AddressFamily.InterNetwork,
SocketType.Raw, ProtocolType.Icmp);
IPHostEntry iphe = Dns.Resolve(argv[0]);
IPEndPoint iep = new IPEndPoint(iphe.AddressList[0], 0);
EndPoint ep = (EndPoint)iep;
ICMP packet = new ICMP();
packet.Type = 0x08;
packet.Code = 0x00;
packet.Checksum = 0;
Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 0, 2);
Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 2, 2);
data = Encoding.ASCII.GetBytes("test packet");
Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length);
packet.MessageSize = data.Length + 4;
int packetsize = packet.MessageSize + 4;
UInt16 chcksum = packet.getCchecksum();
packet.Checksum = chcksum;
host.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 3000);
int badcount = 0;
for (int i = 1; i < 50; i++) {
host.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.IpTimeToLive, i);
timestart = Environment.TickCount;
host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep);
try {
data = new byte[1024];
recv = host.ReceiveFrom(data, ref ep);
timestop = Environment.TickCount;
ICMP response = new ICMP(data, recv);
if (response.Type == 11)
Console.WriteLine("hop {0}: response from {1}, {2}ms",
i, ep.ToString(), timestop - timestart);
if (response.Type == 0) {
Console.WriteLine("{0} reached in {1} hops, {2}ms.",
ep.ToString(), i, timestop - timestart);
break;
59
}
badcount = 0;
} catch (SocketException) {
Console.WriteLine("hop {0}: No response from remote host", i);
badcount++;
if (badcount == 5) {
Console.WriteLine("Unable to contact remote host");
break;
}
}
}
host.Close();
}
}
3.2. Giao thc SMTP, POP3
60
MAIL
RCPT
DATA
RSET
VRFY
NOOP
QUIT
SEND
M t
Hello. S dng xc nh ngi gi in. Lnh ny ny i
km vi tn ca host gi in. Trong ESTMP (extended
protocol), th lnh ny s l EHLO.
Khi to mt giao dch gi th. N kt hp "from" xc nh
ngi gi th.
Xc nh ngi nhn th.
Thng bo bt u ni dung thc s ca bc in (phn thn
ca th). D liu c m thnh dng m 128-bit ASCII v n
c kt thc vi mt dng n cha du chm (.).
Hu b giao dch th
S dng xc thc ngi nhn th.
N l lnh "no operation" xc nh khng thc hin hnh
ng g
Thot khi tin trnh kt thc
Cho host nhn bit rng th cn phi gi n u cui khc.
- Mt s lnh ca POP3
USER Xc nh username
PASS Xc nh password
STAT Yu cu v trng thi ca hp th nh s lng th v ln ca th
LIST Hin danh sch ca th
RETR Nhn th
DELE Xo mt bc th xc nh
NOOP Khng lm g c
RSET Khi phc li nh th xo (rollback)
QUIT Thc hin vic thay i v thot ra
3.2.2. Ci t SMTP, POP3 Client/Server
Vit chng trnh gi Mail n gin theo giao thc SMTP
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
class Program {
static void Main(string[] args) {
string nguoigui, nguoinhan, tieude,body;
string diachimaychu;
int portmaychu;
Console.Write("Nhap di chu SMTP Server:");
diachimaychu = Console.ReadLine();
Console.Write("Nhap cong cua may chu:");
portmaychu = int.Parse(Console.ReadLine());
Console.Write("Nhap dia chi nguoi gui:");
nguoigui = Console.ReadLine();
Console.Write("Nhap dia chi nguoi nhan:");
nguoinhan = Console.ReadLine();
Console.Write("Nhap tieu de buc thu:");
tieude = Console.ReadLine();
Console.Write("Nhap noi dung buc thu:");
body= Console.ReadLine();
//Tao Endpoit cua may chu
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(diachimaychu), portmaychu);
TcpClient client = new TcpClient();
client.Connect(iep);
string Data = "Helo";
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine(Data);
sw.Flush();
//Doc thong bao tu Server gui ve va xu ly neu can thiet
Console.WriteLine(sr.ReadLine());
63
64
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Net;
using System.Net.Sockets;
namespace MyPop3 {
public partial class Form1 : Form {
TcpClient popclient;
StreamReader sr;
StreamWriter sw;
public Form1() {
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
65
}
private void btLogin_Click(object sender, EventArgs e) {
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(txtPOP.Text),
int.Parse(txtPort.Text));
popclient = new TcpClient();
popclient.Connect(iep);
sr = new StreamReader(popclient.GetStream());
sw = new StreamWriter(popclient.GetStream());
sr.ReadLine();
string data = "";
data = "User " + txtUser.Text;
sw.WriteLine(data);
sw.Flush();
sr.ReadLine();
data = "PASS " + txtPass.Text;
sw.WriteLine(data);
sw.Flush();
sr.ReadLine();
data = "LIST";
sw.WriteLine(data);
sw.Flush();
lstHeader.Items.Clear();
string s = sr.ReadLine();
char[] ch = { ' ' };
string[] tam = s.Split(ch);
//MessageBox.Show("so buc thu la:" + tam[1]);
while ((s = sr.ReadLine()) != ".") {
lstHeader.Items.Add(s);
}
}
private void lstHeader_SelectedIndexChanged(object sender, EventArgs e) {
int i = lstHeader.SelectedIndex + 1;
//Lay buc thu ve va tien hanh phan tich
string data = "RETR " + i.ToString();
sw.WriteLine(data);
sw.Flush();
string s;
//MessageBox.Show(sr.ReadLine());
//Lay phan header
while ((s = sr.ReadLine().Trim()) != null) {
//MessageBox.Show(s);
if (s.Length == 0) break;
if (s.ToUpper().StartsWith("DATE")) {
DateTime dt=DateTime.Parse(s.Substring(5, s.Length - 5));
txtDate.Text = dt.ToShortDateString() +" " +dt.ToLongTimeString();
}
if (s.ToUpper().StartsWith("FROM"))
66
(bao gm text,
tham chiu ti 10
nh dng jpeg)
time
6. Cc bc t 1 n 5 c lp
li cho tng i tng trong
10 i tng jpeg
C hai kiu thng ip HTTP l yu cu (Request) v tr li (Response). Cc
thng ip c nh dng kiu m ASCII.
nh dng thng ip yu cu HTTP
68
Dng yu cu
(lnh GET, POST,
HEAD)
Nhng dng header
CR,LF,k hiu kt
thc thng ip
HTTP/1.0 200 OK
Date: Thu, 06 Aug 1998 12:00:15 GMT
Server: Apache/1.3.0 (Unix)
Last-Modified: Mon, 22 Jun 1998 ...
Content-Length: 6821
Content-Type: text/html
data data data data data ...
d liu,e.g.,
tp html c
yu cu
69
M trng thi trong thng ip HTTP Response: c ghi dng u tin trong thng
ip response t server v client.
Mt s m thng gp:
200 OK
Yu cu thnh cng,cc i tng c yu cu phn sau thng ip.
301 Moved Permanently
i tng c yu cu c chuyn v a ch mi ca i tng c t
trong trng Location:
400 Bad Request
Server khng hiu c thng ip yu cu
404 Not Found
Ti liu c yu cu khng c trong server
505 HTTP Version Not Supported
Server khng h tr version ca giao thc HTTP.
- kim tra cc lnh ca HTTP bn pha Client chng ta c th thc hin nh sau:
+ Telnet ti Web server
70
telnet www.eurecom.fr 80
To kt ni TCP cng 80
(cng mc nh cho HTTP server)
at www.eurecom.fr.
Gi thng ip yu cu ly tp
Index.html trong th mc ~ross
v client
using System.Net;
using System.Net.Sockets;
public class SimpleWebServer {
public void StartListening(int port) {
IPEndPoint LocalEndPoint = new IPEndPoint(IPAddress.Any, 8080);
TcpListener server = new TcpListener(LocalEndPoint);
server.Start();
while (true) {
TcpClient client = server.AcceptTcpClient(); // Cho doi ket noi
processClientRequest(client);
}
}
//X l yu cu ca mi my khch
private void processClientRequest(TcpClient client) {
Console.WriteLine("May khach su dung cong: " +
(client.Client.RemoteEndPoint as IPEndPoint).Port + "; Dia chi IP may khach: " +
client.Client.RemoteEndPoint.ToString() + "\n");
Console.WriteLine("Yeu cau: ");
readRequest(client);
sendResponse(client);
client.Close();
}
//c phn header ca gi d liu gi t my khch
private void readRequest(TcpClient client) {
StreamReader request = new StreamReader(client.GetStream());
String nextLine;
while (null != (nextLine = request.ReadLine())) {
if (nextLine.Equals("")) {
break;
} else {
Console.WriteLine(nextLine);
}
}
Console.WriteLine("---------------------------------------");
}
//Phn hi yu cu cho my khch
private void sendResponse(TcpClient client) {
StreamWriter response = new StreamWriter(client.GetStream());
response.Write(_mainPage);
response.Flush();
}
//Mi phn hi v trnh duyt
private const String _mainPage =
"HTTP/1.0 200 OK\n" +
73
"Content-type: text/html\n" +
"Connection: close\n" +
"\n<HTML>\n" +
"<HEAD>\n" +
"<TITLE>Hello World</TITLE>\n" +
"</HEAD>\n" +
"<BODY> <a href = \"localhost\"> Hello World </a></BODY>\n" +
"</HTML> \n\n";
}
class TestWebServer {
public static void Main(String[] args) {
SimpleWebServer webServer1 = new SimpleWebServer();
webServer1.StartListening(8080);
}
}
3.4. Giao thc FTP
74
FTP l mt giao thc dng client/server truyn thng, tuy nhin thut ng client thng
thng c thay th bng thut ng user ngi dng do thc t l ngi s dng
mi l i tng trc tip thao tc cc lnh FTP trn my clients. B phn mm FTP
c ci t trn mt thit b c gi l mt tin trnh. Phn mm FTP c ci t
trn my Server c gi l tin trnh Server-FTP, v phn trn my client c gi l
tin trnh User-FTP.
Knh iu khin v knh d liu trong FTP
Mt khi nim ct yu m ta cn phi nm v FTP l: mc d giao thc ny s dng
kt ni TCP, nhng n khng ch dng mt knh TCP nh phn ln cc giao thc
truyn thng khc. M hnh FTP chia qu trnh truyn thng gia b phn Server vi
b phn client ra lm hai knh logic:
- Knh iu khin: y l knh logic TCP c dng khi to mt phin kt ni
FTP. N c duy tr xuyn sut phin kt ni FTP v c s dng ch truyn cc
thng tin iu khin, nh cc lnh v cc hi p trong FTP. N khng c dng
truyn file
- Knh d liu: Mi khi d liu c truyn t server ti client, mt knh kt ni TCP
nht nh li c khi to gia chng. D liu c truyn i qua knh kt ni ny
do n c gi l knh d liu. Khi file c truyn xong, knh ny c ngt.
Vic s dng cc knh ring l nh vy to ra s linh hot trong vic truyn truyn d
liu m ta s thy trong cc phn tip theo. Tuy nhin, n cng to cho FTP phc
tp nht nh.
Cc tin trnh v thut ng trong FTP
Do cc chc nng iu khin v d liu s dng cc knh khc nhau, nn m hnh hot
ng ca FTP cng chia phn mm trn mi thit b ra lm hai thnh phn logic tng
ng vi mi knh. Thnh phn Protocol Interpreter (PI) l thnh phn qun l knh
iu khin, vi chc nng pht v nhn lnh. Thnh phn Data Transfer Process (DTP)
c chc nng gi v nhn d liu gia pha client vi server. Ngoi ra, cung cp cho
tin trnh bn pha ngi dng cn c thm thnh phn th ba l giao din ngi dng
FTP - thnh phn ny khng c pha server.
Do , c hai tin trnh xy ra pha server, v ba tin trnh pha client. Cc tin
trnh ny c gn vi m hnh FTP m t chi tit hot ng ca giao thc FTP.
Di y l hnh i chiu cc tin trnh vo trong m hnh FTP:
75
cng
bt
lm
cng
ngun
trong
phin
kt
ni
TCP.
Khi TCP c ci t xong, knh iu khin gia cc thit b s c thit lp, cho
php cc lnh c truyn t User-PI ti Server-PI, v Server-PI s p tr kt qu l
cc m thng bo. Bc u tin sau khi knh i vo hot ng l bc ng nhp
ca ngi dng (login sequence). Bc ny c hai mc ch:
- Access Control - iu khin truy cp: qu trnh chng thc cho php hn ch truy
cp ti server vi nhng ngi dng nht nh. N cng cho php server iu khin
loi
truy
cp
nh
th
no
i
vi
tng
ngi
dng.
- Resource Selection - Chn ngun cung cp: Bng vic nhn dng ngi dng to kt
ni, FTP server c th a ra quyt nh s cung cp nhng ngun no cho ngi dng
c nhn dng .
Trnh t truy cp v chng thc FTP
Quy lut chng thc trong FTP kh n gin, ch l cung cp username/password.
Trnh t ca vic chng thc nh sau:
1 - ngi dng gi mt username t User-PI ti Server-PI bng lnh USER. Sau
password
ca
ngi
dng
c
gi
i
bng
lnh
PASS.
2 - Server kim tra tn ngi dng v password trong database ngi dng ca n.
Nu ngi dng hp l, server s gi tr mt thng bo ti ngi dng rng phin kt
77
cho c hot ng chuyn file trc tip (gi hoc nhn mt file) cng nh i vi vic
truyn d liu ngm, nh l yu cu mt danh sch file trong th mc no trn
server.
Chun FTP ch nh hai phng thc khc nhau to ra knh d liu. Khc bit
chnh ca hai phng thc l mt thit b: pha client hay pha server l pha
a ra yu cu khi to kt ni. iu ny nghe qua c v kh n gin, nhng k thc
n li kh quan trng.
Kt ni knh d liu dng ch ng
Phng thc u tin i khi cn c gi l kt ni knh d liu dng thng thng
(v n l phng php mc nh) v i khi c gi l kt ni dng ch ng ( i
chiu vi dng kt ni b ng m ta s xt phn sau). Trong dng kt ni ny, pha
Server-DTP khi to knh d liu bng vic m mt cng TCP cho pha User-DTP.
Pha server s dng cng c dnh ring, l cng 20 cho knh d liu. Trn my
client, mt gi tr cng c chn theo mc nh chnh l cng c s dng i vi
knh iu khin, tuy nhin pha client s lun chn hai cng ring bit cho hai knh
ny.
Gi s pha User-PI thit lp mt kt ni iu khin t cng bt k ca n l 1678 ti
cng iu khin trn server l cng 21. Khi , to mt knh d liu cho vic
truyn d liu, pha Server-PI s bo cho pha Server-DTP khi to mt knh kt ni
TCP t cng 20 ti cng 1678 ca pha client. Sau khi pha client chp nhn knh
c khi to, d liu s c truyn i.
Thc t, vic s dng cng mt cng cho c knh d liu v knh iu khin khng
phi l mt hay, n lm cho hot ng ca FTP tr nn phc tp. Do , pha client
nn ch nh s dng mt cng khc bng vic s dng lnh PORT trc khi truyn d
liu. V d: gi s pha client ch nh cng 1742 vi lnh PORT. Pha Server-DTP sau
s to ra mt kt ni t cng 20 ca n ti cng 1742 pha client thay v cng 1678
nh mc nh. Qu trnh ny c m t trong hnh di y.
79
Thng thng, i vi knh d liu FTP, pha server s khi to vic truyn d liu
bng cch m kt ni d liu ti client.
Trong trng hp trn, pha client trc tin s a ra lnh PORT yu cu server s
dng cng 1742. Sau , server s m kt ni knh d liu t cng 20 mc nh ca n
ti cng 1742 pha client. D liu sau s c truyn gia cc thit b qua cc cng
ny.
Kt ni knh d liu dng b ng
Phng php k tip c gi l kt ni d liu dng b ng. Pha client s nhn
server l pha b ng, lm nhim v chp nhn mt yu cu kt ni knh d liu c
khi to t pha client. Server tr li li pha client vi a ch IP cng nh a ch
cng m n s s dng. Pha Server-DTP sau s lng nghe mt kt ni TCP t pha
User-DTP trn cng ny.
Mc nh, pha client s dng cng mt cng i vi c hai knh iu khin v d liu
nh trong trng hp kt ni ch ng trn. Tuy nhin, y, mt ln na pha
client c th chn s dng mt gi tr cng khc cho knh d liu. Ta s xt li v d
trn mt ln na, vi cng iu khin pha client l 1678 ti cng 21 pha server.
80
Pha client s s dng lnh PASV yu cu server rng n mun dng phng thc
iu khin d liu b ng. Pha Server-PI s tr li li pha client vi mt gi tr cng
m client s s dng, t cng 2223 trn n. Sau pha Server PI s hng cho pha
Server-DTP lng nghe trn cng 2223. Pha User-PI cng s hng cho pha UserDTP to mt phin kt ni t cng 1742 pha client ti cng 2223 pha server. Sau khi
Server
chp
nhn
kt
ni
ny,
liu
bt
truyn
i.
thng ca h.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Program {
static void Main(string[] args) {
string rootDir = "C:/MyFTP";
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2121);
TcpListener server = new TcpListener(iep);
server.Start();
TcpClient client = server.AcceptTcpClient();
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine("220 Chao mung ket noi toi MyFTP");
sw.Flush();
while (true) {
string request = sr.ReadLine();
string command="";
if(request.Length!=0)
command = request.Substring(0, 4);
switch (command.ToUpper().Trim()) {
case "USER": {
sw.WriteLine("331. Nhap pass vao");
sw.Flush();
//sw.Close();
Console.WriteLine(request);
break;
}
case "PASS": {
sw.WriteLine("230. Dang nhap thanh cong");
sw.Flush();
Console.WriteLine(request);
break;
}
84
case "MKD": {
string folderName = request.Substring(4, request.Length - 4);
folderName = rootDir + "/" + folderName.Trim();
try {
Directory.CreateDirectory(folderName);
sw.WriteLine("150 Tao thu muc thanh cong");
sw.Flush();
}catch(IOException){
sw.WriteLine("550 Tao thu muc co loi");
sw.Flush();
}
break;
}
case "RETR": {
string fileName = request.Substring(4, request.Length - 4);
fileName = rootDir + "/" + fileName.Trim();
try {
if (File.Exists(fileName)) {
//Gui noi dung file ve cho client xu ly
sw.WriteLine("150 Truyen File thanh cong");
sw.Flush();
FileStream fs = new FileStream(fileName, FileMode.Open);
long totalLenght = fs.Length;
byte[] data = new byte[totalLenght];
fs.Read(data, 0, data.Length);
sw.Write(totalLenght);
char[] kt = Encoding.ASCII.GetChars(data);
sw.Write(kt,0,data.Length);
sw.Flush();
fs.Close();
} else {
sw.WriteLine("550 File khong ton tai tren server");
sw.Flush();
}
} catch (IOException) {
sw.WriteLine("550 Khong truyen duoc file");
sw.Flush();
}
break;
}
case "STOR": {
string fileName =
request.Substring(request.LastIndexOf("/"),request.Length-request.LastIndexOf("/"));
fileName = rootDir + "/" + fileName.Trim();
try {
FileStream fs = new FileStream(fileName, FileMode.CreateNew);
long totalLength=sr.Read();
byte[] data = new byte[totalLength];
char[] kt = Encoding.ASCII.GetChars(data);
85
}
}
if (input.ToUpper().Equals("QUIT")) break;
}
sr.Close();
sw.Close();
client.Close();
}
}
}
3.5. DNS (Domain Name Server)
88
a NSI Herndon, VA
c PSInet Herndon, VA
d U Maryland College Park, MD
g DISA Vienna, VA
h ARL Aberdeen, MD
k RIPE London
i NORDUnet Stockholm
m WIDE Tokyo
e NASA Mt View, CA
f Internet Software C. Palo Alto,
CA
4
5
requesting host
surf.eurecom.fr
gaia.cs.umass.edu
89
C th khng bit
authoritative name
server
C th bit name
server trung gian
,nh c th yu
cu tm authoritative
name server
2
3
dns.eurecom.fr
requesting host
surf.eurecom.fr
gaia.cs.umass.edu
DNS example
iterated query
2
3
4
7
dns.eurecom.fr
requesting host
surf.eurecom.fr
gaia.cs.umass.edu
90
Type=A
Type=CNAME
name : hostname
name : tn b danh cho mt tn
value : IP address
thc no : e.g www.ibm.com
l tn b danh ca
Type=NS
servereast.backup2.ibm.com
name : domain (e.g. foo.com)
value : l tn thc
value : a ch IP
authoritative name server cho Type=MX
tn min
value : tn ca mailserver
do {
if ((len & 0xC0) == 0xC0) {
if (position >= data.GetLength(0)) {
return -1;
}
offset = ((len & 0x3F) << 8) | (data[position++] &
0xFF);
proc(offset, data, ref name);
return position;
} else {
if ((position + len) > data.GetLength(0)) {
return -1;
}
name += Encoding.ASCII.GetString(data, position, len);
position += len;
}
if (position > data.GetLength(0)) {
return -1;
}
len = data[position++] & 0xFF;
if (len != 0) {
name += ".";
}
}
while (len != 0);
return position;
}
}
3.6 Tho lun v cc ng dng khc thng gp
3.7 Bi tp p dng
93
- Lp th nht : Lp giao din (giao tip vi ngi s dng) : ch thun x l vic giao
tip vi ngi s dng, nhp xut, m khng thc hin vic tnh ton, kim tra, x
l, hay cc thao tc lin quan n c s d liu.
- Lp th hai : Lp x l : Lp ny chuyn thc hin cc x l , kim tra cc rng
buc, cc qui tc ng x ca phn mm , cc chc nng ct yu, Vic thc hin ny
c lp vi cch thit k cng nh ci t giao din. Thng tin cho lp ny thc hin
cc x l ca mnh c ly t lp giao din.
- Lp th ba : Lp d liu : Lp ny chuyn thc hin cc cng vic lin quan n d
liu. D liu c th ly t c s d liu (Access, SQL Server ) hoc tp tin (text,
binary, XML ). i vi c s d liu, lp ny thc hin kt ni trc tip vi c s
d liu v thc hin tt c cc thao tc lin quan n c s d liu m phn mm cn
thit. i vi tp tin, lp ny thc hin vic c, ghi tp tin theo yu cu ca phn
mm. Vic thc hin ny do lp x l gi.
94
GUI
Browser
Local
Web
Data tier
Logical view
Business tier
Physical view
Web
Application
Web
Business logic
Data Access
Data
V d minh ha:
Xy dng chng trnh tnh tng 2 phn s theo kin trc 3 lp. Theo d
liu ca phn s c c ln t tp tin XML, kt qu sau khi c tnh s c ghi
xung tp tin XML.
Cch lm thng thng l mi vic u c y vo trong 1 form v x l
trc tip trong form . Tuy nhin, khi c s thay i xy ra v giao din, x l, hay
d liu th vic chnh sa kh kh khn. Do vy, vic xy dng theo kin trc 3 lp s
khc phc nhc im ny.
Kin trc ca chng trnh nh sau:
95
96
mauso = 0;
return;
}
XmlElement ele = doc.DocumentElement;
tuso = int.Parse(ele.SelectSingleNode("Tu_so").InnerText);
mauso = int.Parse(ele.SelectSingleNode("Mau_so").InnerText);
}
Thc hin ci t hm ghi phn s vi tham s truyn vo l ng dn file XML
public void GhiPhanSo(string strFilename)
{
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("PHANSO");
doc.AppendChild(root);
XmlElement ele_Tuso =
root.OwnerDocument.CreateElement("Tu_so");
ele_Tuso.InnerText = this.tuso.ToString();
root.AppendChild(ele_Tuso);
XmlElement ele_Mauso =
root.OwnerDocument.CreateElement("Mau_so");
ele_Mauso.InnerText = this.mauso.ToString();
root.AppendChild(ele_Mauso);
LT_XML.GhiTaiLieu(strFilename,doc);
}
Lp lu tr XML (LT_XML)
Vic load v save XmlDocument c tch ra thnh mt lp ring l lp LT_XML
public static XmlDocument DocTaiLieu(string strFilename) {
XmlDocument kq = new XmlDocument();
try {
kq.Load(strFilename);
}
catch{
return null;
}
return kq;
}
public static void GhiTaiLieu(string strFilename, XmlDocument doc) {
try{
doc.Save(strFilename);
}
catch{
}
}
Lp x l phn s (XL_PHANSO)
98
this.th_ps.tuso = tuso;
this.th_ps.mauso = mauso;
}
rt gn ta cn tnh c chung ln nht, c th ci t hm ny chung vi lp
XL_PHANSO
public int TimMaxUocChung(int a, int b)
{
while(a!=b)
{
if(a>b)
a -= b;
else
b -= a;
}
return a;
}
Thc hin ci t mn hnh chnh (MainFrm)
Ch :
Khng ph thuc phng php lp trnh.
Mi nghip v khng nht thit ch c gii quyt bi 3 i tng.
Khng l mt kin trc siu vit.
4.2. Remoting
host n trong IIS. Web Services cho php cc ng dng c th giao tip vi nhau m
khng ph thuc platform, ngn ng lp trnh, Tuy nhin Web Services l mt mi
trng stateless, c ngha l n khng lu li bt k trng thi g ca ln gi trc v
n cng khng bit g v pha client ang thc hin request. Client v server Web
Services ch c th trao i vi nhau bng cc thng ip SOAP. Nhng iu sau y
l cc im khc nhau chnh gia .NET Remoting v Web Serices, chng cng l
nhng nhn t ta chn la gia 2 cng ngh ny:
ASP.NET Web Services ch c th c truy xut qua HTTP cn .NET Remoting c
th c dng trn nhiu giao thc khc nhau nh TCP, HTTP.
Web Services l mt mi trng stateless. Khi c mt request t pha client, s c
mt object mi c to ra thc hin request trn server. Cn .NET Remoting
li h tr nhiu la chn state management v c th thc hin nhiu request t mt
client, ng thi c h tr callbacks.
Web Services serialize cc i tng thnh XML bn trong SOAP message v v th
c th truyn ti thng tin ca bt c thnh phn no min c th chuyn thnh XML.
Cn i vi .NET Remoting th ty giao thc v nh dng message m n c th
truyn i thng tin nh th no. Ngoi ra theo nh gii thiu th .NET Remoting c
cho php i tng c truyn vo theo c kiu tham chiu(reference) v tham tr
(value)
Web services c th hot ng trn cc platform mi trng khc nhau trong khi
.NET Remoting yu cu pha clients phi l .NET application.
Channels
- Trong k thut .NET Remoting th Channel c hiu nh l mt knh giao tip
gia client v server. Mt object t client s thng qua Channel giao tip vi object
pha server, Channel s truyn ti nhng message t hai pha. Nh gii thiu pha trn
th c hai channel chnh l TcpChannel v HttpChannel tng ng vi cc giao thc
TCP v HTTP. Ngoi ra, TcpChannel v HttpChannel u c kh nng extend thnh
nhng Custom Channel ca bn.
Lm sao to mt Object c th Remote c trong .NET Remoting?
- Mt Object remote c ch l mt object thng thng nhng phi c inherit t
MarshalByRefObject. on code sample hnh 4.2 l mt v d n gin v
Remotable Object. i tng SampleObject trong hnh c mt s method n gin tr
v php tnh tng, hiu, tch, thng ca hai s nguyn. Gi tr tr v ca hm l kiu
s nguyn, kiu built-in ca .NET framework. Nu bn mun tr v kiu d liu bn t
nh ngha, hoc mt instance ca class bn nh ngha th lp ca bn phi c
khai bo vi attribute Serializable.
using System;
public class SampleObject: MarshalByRefObject
{
public int Add(int a, int b)
{
int c = a + b;
103
return c;
}
public int Subtract(int a, int b)
{
int c = a - b;
return c;
}
public int Multiply(int a, int b)
{
int c = a * b;
return c;
}
public int Divide(int a, int b)
{
int c;
if (b != 0)
c = a / b;
else
c = 0;
return c;
}
}
104
106
108
ngh chun l SOAP. SOAP l giao thc nm gia tng vn chuyn v tng m
t thng tin v dch v, SOAP cho php ngi dng triu gi mt service t xa
thng qua mt message XML.
Tng m t dch v (Service Description) vi cng ngh chun l WSDL v
XML. WSDL l mt ngn ng m t giao tip v thc thi da trn XML. Web
service s dng ngn ng WSDL truyn cc tham s v cc loi d liu cho
S truyn ti d liu
SOAP Binding
Thut ng m t lm th no mt thng ip SOAP tng tc c vi mt giao thc vn
chuyn nh HTTP, SMTP hay FTP di chuyn trn Internet. iu quan trng l SOAP di
chuyn bng mt giao thc chun lin lc vi cc sn phm Web Services khc.
Trc SOAP, nhiu ngi pht trin to ra cc phng php ca ring h chuyn ti
mt ti liu XML trn mng. Cc cch ny vn hot ng tt trong phm vi mt nhm c th.
Tuy nhin khi bn cn lm vic vi mt nhm khc trong hay bn ngoi cng ty th iu
ny tr nn kh khn v phi hun luyn v c th thay i lm vic vi vic truyn ti ti
liu XML m h ang s dng. Bng cch s dng mt ti liu XML chun trn cc giao thc
chun, cng vic cn lm khi cng tc vi nhau s c gim thiu ti a
SOAP Application
Mt ng dng SOAP n gin l mt ng dng dng SOAP theo mt vi cch khc nhau. Vi
ng dng hon ton da trn chun SOAP, nh l Web Services c phiu, hoc dng chun
SOAP nhn m v cc cp nht ca phn mm. Ch l mt ng dng c th to, s dng
hoc l nt trung gian ca Web Services.
SOAP Node
Trch nhim ca mt nt c th bao gm gi, nhn, x l hoc truyn ti li mt thng ip
SOAP. Mt nt ch l mt phn nh ca phn mm, x l mt ti liu SOAP ph thuc vo
110
vai tr ca n. Bn cnh vic truyn d liu, mt nt c trch nhim m bo thng tin XML
trong ti liu SOAP phi ng ng php theo chun SOAP.
SOAP Role
Mt vai tr ca SOAP nh ngha mt nt c th hot ng nh th no. N c th l nt gi,
nhn hoc nt trung gian.
SOAP Sender
Nt gi l nt gi yu cu SOAP. Nu bn ngh n v d ca ng dng khch ch th khi
ng dng khch thc hin yu cu, n gi thng ip ti ng dng ch yu cu vi thng
tin.
SOAP Receiver
Ngc li vi SOAP sender l nt nhn.
SOAP Intermediary
Mt nt trung gian c th xem mt thng ip SOAP v tng tc trn vi phn thng tin ca
thng ip, v chuyn n v tr k tip ca thng ip. Mt nt trung gian thng hot ng
nh mt router. Mt router s xem xt thng tin ca gi tin chuyn trn mng, tm im k
tip ca gi tin v chuyn gi tin n .
Message Path
Mt thng ip SOAP di chuyn t pha bn gi n pha bn nhn thng ip thng qua
nhiu nt trung gian. Tuyn ng i ca thng ip c gi l mt Message Path.
SOAP Feature
Mt c im SOAP l mt phn chc nng ca phn mm h tr chc nng SOAP.
SOAP Message
y l ti liu XML c truyn bi mt nt SOAP gi hoc nhn. Mt nt gi hoc nt
khch to ra mt ti liu XML cha thng tin m pha bn khch cn t pha ch. Mt khi ti
liu c truyn, pha bn ch phn gii thng tin trong ti liu truy xut cc gi tr khc
nhau v to mt thng ip SOAP mi phn hi.
SOAP Envelope
y l phn t gc ca ti liu SOAP XML. Ti liu SOAP cha nhiu nh ngha khng gian
tn (namespace) nhng cc phn t lin quan ti thng ip SOAP s c ENV: l tip u
ng.
SOAP Header
111
Phn u ca mt thng ip SOAP cha mt khi thng tin u trong ti liu XML nh
tuyn v x l thng ip SOAP. D liu ny tch ri khi phn thn ca ti liu c cha
thng tin lin quan n i tng c gi.
SOAP Body
Phn thn ca SOAP tht s cha thng tin ca i tng x l thng tin. Phn thn sau
khi c phn tch s tr thnh i tng. i tng x l thng tin v kt qu c t
trong phn thn ca ti liu tr v.
SOAP Fault
y l mt phn thng tin ca SOAP cha thng tin n bt k li g xy ra ti mt nt
SOAP.
- To Web Method
112
- Chn hm Add
113
114
- To mn hnh:
115
- Vit hm x l nt nhn:
116
117