1
CHƯƠNG 1: CÁC KI N TH C CƠ B N V M NG MÁY TÍNH.......................................3
1.1. Mô hình tham kh o 7 t ng OSI........................................................................................3
1.2. H giao th c TCP/IP........................................................................................................5
1.3. So sánh gi a hai giao th c TCP và UDP.........................................................................6
1.4. C ng giao th c.................................................................................................................7
1.5. ð a ch IP, các ñ a ch IP dành riêng................................................................................7
1.6. ð a ch tên mi n: lo i A, lo i MX.. .................................................................................8
1.7. M t s giao th c t ng ng d ng: HTTP, SMTP, POP3, FTP... ...................................8
CHƯƠNG 2: L P TRÌNH M NG TRONG .NET FRAMEWORK ........................................9
2.1. Socket hư ng k t n i (TCP Socket) ................................................................................9
2.1.1. Gi i thi u v NameSpace System.Net và System.Net.Sockets..............................10
2.1.2. Vi t chương trình cho phía máy ch .......................................................................11
2.1.3. Vi t chương trình cho phía máy khách...................................................................13
2.1.4. S d ng các lu ng nh p xu t v i Socket................................................................14
2.2. Socket không hư ng k t n i (UDP Socket)...................................................................17
2.2.1. Vi t chương trình cho phía máy ch .......................................................................17
2.2.2. Vi t chương trình cho phía máy khách...................................................................18
2.2.3. S d ng l p System.IO.MemoryStream ñ t o vùng ñ m nh p xu t.....................20
2.3. S d ng các l p h tr ñư c xây d ng t l p Soket .....................................................20
2.3.1. L p TCPClient........................................................................................................21
2.3.2. L p TCPListener ....................................................................................................22
2.3.3. L p UDPClient .......................................................................................................24
2.4. Socket không ñ ng b ....................................................................................................26
2.4.1. Mô hình x lý s ki n c a windows.......................................................................26
2.4.2. S d ng Socket không ñ ng b ..............................................................................27
2.4.3. Ví d v Socket không ñ ng b ..............................................................................28
2.4.4. S d ng các phương th c Non-blocking ................................................................35
2.5. S d ng Thread trong các ng d ng m ng....................................................................39
2.5.1. S d ng Thread trong chương trình .Net................................................................40
2.5.2. S d ng Thread trong các chương trình Server......................................................41
2.5.3. S d ng Thread ñ g i/nh n d li u.......................................................................41
2.5.4. S d ng ThreadPool trong các chương trình .Net ..................................................43
2.5.5. S d ng ThreadPool trong các chương trình Server...............................................47
2.6. K thu t IP Multicasting................................................................................................48
2.6.1. Broadcasting là gì?..................................................................................................48
2.6.2. S d ng Broadcasting ñ g i d li u ñ n nhi u máy trong m ng c c b ..............48
2.6.3. Multicasting là gì? ..................................................................................................49
2.6.4. Socket Multicasting trong .Net ...............................................................................50
2.7 Bài t p áp d ng ...............................................................................................................53
CHƯƠNG 3: XÂY D NG NG D NG M NG...................................................................55
3.1. Giao th c ICMP.............................................................................................................55
3.1.1. S d ng Raw Socket...............................................................................................55
3.1.2. S d ng giao th c ICMP và Raw Socket ñ xây d ng chương trình Ping.............57
3.1.3. S d ng giao th c ICMP và Raw Socket ñ xây d ng chương trình TraceRoute .58
3.2. Giao th c SMTP, POP3.................................................................................................60
3.2.1. Cơ b n v h th ng Mail và giao th c SMTP, POP3 .............................................60
3.2.2. Cài ñ t SMTP, POP3 Client/Server........................................................................60
3.3. Giao th c HTTP.............................................................................................................67
3.3.1. Cơ b n v giao th c HTTP .....................................................................................67
3.3.2. Cài ñ t HTTP Client/Server....................................................................................68
3.4. Giao th c FTP................................................................................................................74
3.4.1. Cơ b n v giao th c FTP ........................................................................................74
3.4.2. Cài ñ t FTP Client/Server.......................................................................................84
2
3.5. DNS (Domain Name Server).........................................................................................88
3.5.1. V n ñ phân gi i tên mi n ......................................................................................88
3.5.2. Tri n khai DNS MX (Mail Exchange) ...................................................................89
3.6 Th o lu n v các ng d ng khác thư ng g p .................................................................93
3.7 Bài t p áp d ng ...............................................................................................................93
CHƯƠNG 4: XÂY D NG NG D NG NHI U L P ..........................................................94
4.1. Mô hình 2 l p (two tier), 3 l p (three tier) và n l p. .....................................................94
4.2. Remoting........................................................................................................................98
4.2.1. Gi i thi u v Remoting.........................................................................................102
4.2.2. Khai báo, cài ñ t và ñăng ký giao di n t xa........................................................102
4.2.3. Tri u g i phương th c t xa .................................................................................107
4.3. Web Serive...................................................................................................................107
4.3.1. Gi i thi u v Web Serives ....................................................................................107
4.3.2. Giao th c SOAP ...................................................................................................109
4.3.3. Xây d ng Web Services........................................................................................112
4.3.4. Tri u g i Web Services t ng d ng .NET, Java và các ngôn ng khác .............114
4.4 Th o lu n v các ng d ng phân tán ............................................................................116
4.5. Bài t p áp d ng ............................................................................................................116
3
CHƯƠNG 1: CÁC KI N TH C CƠ B N V M NG MÁY TÍNH
1.1. Mô hình tham kh o 7 t ng OSI
Mô hình k t n i h th ng m ñư c T ch c qu c t v tiêu chu n hoá ISO
(International Organizaiton for Standardization) ñưa ra nh m cung c p m t mô hình
chu n cho các nhà s n xu t và cung c p s n ph m vi n thông áp d ng theo ñ phát
tri n các s n ph m vi n thông. Ý tư ng mô hình hoá ñư c t o ra còn nh m h tr cho
vi c k t n i gi a các h th ng và modun hoá các thành ph n ph c v m ng vi n thông.
a. Ch c năng c a mô hình OSI:
- Cung c p ki n th c v ho t ñ ng c a k t n i liên m ng
- ðưa ra trình t công vi c ñ thi t l p và th c hi n m t giao th c cho k t n i các thi t
b trên m ng.
Mô hình OSI còn có m t s thu n l i sau :
- Chia nh các ho t ñ ng ph c t p c a m ng thành các ph n công vi c ñơn gi n.
- Cho phép các nhà thi t k có kh năng phát tri n trên t ng modun ch c năng.
- Cung c p các kh năng ñ nh nghĩa các chu n giao ti p có tính tương thích cao
“plug and play” và tích h p nhi u nhà cung c p s n ph m.
b. C u trúc mô hình OSI:
Mô hình OSI g m 7 l p (level), m i l p th c hi n các ch c năng riêng cho ho t ñ ng
k t n i m ng.
Hình 1-1 Mô t b y l p OSI. 4 l p ñ u ñ nh nghĩa cách th c cho ñ u cu i thi t l p k t
n i v i nhau ñ trao ñ i d li u. 3 l p trên dùng ñ phát tri n các ng d ng ñ ñ u
cu i k t n i v i nhau và ngư i dùng.
Aplication
PresentationApplication
(Upper Layer) Session
Transport Layer
Network Layer
Data Link
Physical
Data Lower Layer
Các l p trên
3 l p trên cùng c a mô hình OSI thư ng ñư c g i là các l p ng d ng (Application
layers) hay còn g i là các l p cao. Các l p này thư ng liên quan t i giao ti p v i
ngư i dùng, ñ nh d ng c a d li u và phương th c truy nh p các ng d ng ñó.
Hình 1-2 Mô t các l p trên và cung c p thông tin v i các ch c năng c a nó qua ví
d :
- L p ng d ng: ch c năng giao Telnet, HTTP
4
Application ti p gi a ngư i s d ng và các
chương trình ng d ng
Presentation
- L p trình bày: cách th c chu n
hoá d li u và trình bày s li u
- Có ch c năng ñ c bi t là mã hoá
d li u ngư i s dung
ASSCII
EBCDIC
JPEC
Session
- L p phiên: thi t l p, duy trì và
hu b m t phiên làm vi c
NFS, SQL
Transport Layer
Network Layer
Data Link
Physical
- Application layer : ñây là l p cao nh t trong mô hình. Nó là nơi mà ngư i s
d ng ho c k t n i các chương trình ng d ng v i các th t c cho phép truy nh p vào
m ng.
- Presentation layer : L p presentation cung c p các mã và ch c năng ñ chuy n
ñ i mà ñư c cung c p b i l p ng d ng. Các ch c năng ñó ñ m b o r ng d li u t
l p ng d ng trong m t h th ng có th ñư c ñ c b i l p ng d ng c a m t h th ng
khác. VD : dùng ñ mã hoá d li u t l p ng d ng : như mã hoá nh jpeg , gif. Mã ñó
cho phép ta có th hi n lên trang web .
- Session layer : ñư c s d ng ñ thi t l p, duy trì và k t thúc phiên làm vi c
gi a các l p presentation. Vi c trao ñ i thông tin l p này bao g m yêu c u d ch v
và ñáp ng yêu c u c a các ng d ng trên thi t b khác.
Các l p dư i.
4 l p dư i c a mô hình OSI s d ng ñ ñ nh nghĩa làm th nào ñ d li u ñư c
truy n ñi trong các dây n i v t lý, các thi t b m ng và ñi ñ n tr m ñ u cu i cu i cùng
là ñ n các l p ng d ng. Qu n sách này ta ch quan tâm ñ n 4 l p cu i. Và s xem xét
t ng l p m t cách chi ti t giao thi p gi a các l p trong mô hình OSI:
S d ng phương pháp protocal stack ñ k t n i gi a hai thi t b trong m ng. Protocal
stack là m t t p h p các quy ñ nh dùng ñ ñ nh nghĩa làm th nào ñ d li u truy n
qua m ng.
Ví d v i : TCP/IP m i Layer cho phép d li u truy n qua. Các l p ñó trao ñ i các
thông tin ñ cung c p cu c liên l c gi a hai thi t b trong m ng. Các l p giao ti p v i
nhau s d ng Protocal Data Unit (PDU). Thông tin ñi u khi n c a PDU ñư c thêm
5
vào v i d li u l p trên. Và thông tin ñi u khi n này n m trong trư ng g i là trư ng
header và trailer.
Hình 1-3 Data encapsulation
Application
Presentation
Upper Layer Data Session
TCP Header Upper Layer Data 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 th c TCP/IP
Các t ng c a giao th c TCP/IP so v i c c t ng c a mô hình OSI
Application: Xác nh n quy n, nén d li u và các d ch v cho ngư i dùng
Transport: X lý d li u gi a các h th ng va cung c p vi c truy c p m ng cho các
ng d ng
Network: Tìm ñư ng cho các packet
6
Link: M c OS ho c các thi t b giao ti p m ng trên m t máy tính
M t s ñi m khác nhau c a TCP/IP và mô hình OSI
+ L p ng d ng trong TCP/IP x lý ch c năng c a l p 5,6,7 trong mô hình OSI
+ L p transport trong TCP/IP cung c p c ch UDP truy n không tin c y, transport
trong OSI luôn ñ m b o truy n tin c y
+ TCP/IP là m t t p c a các protocols (m t b giao th c)
+ TCP/IP xây d ng trư c OSI
Quy trình ñóng gói d li u trong mô hình TCP/IP như sau:
1.3. So sánh gi a hai giao th c TCP và UDP
7
1.4. C ng giao th c
Là m t s năm trong kho ng 1..65535 dùng ñ phân bi t gi a 2 ng d ng m ng
v i nhau g n v i ñ a ch IP và Socket
M t s c ng và các giao th c thông d ng:
+ FTP: 21
+ Telnet: 23
+ SMTP: 25
+ POP3: 110
+ HTTP:80
1.5. ð a ch IP, các ñ a ch IP dành riêng
Reverved for future use01111Class E
Multicast address0111Class D
HostidNetid011Class C
HostidNetid01Class B
HostidNetid0Class A
2416843210
Reverved for future use01111Class E
Multicast address0111Class D
HostidNetid011Class C
HostidNetid01Class B
HostidNetid0Class A
2416843210
8
1.6. ð a ch tên mi n: lo i A, lo i MX..
1.7. M t s giao th c t ng ng d ng: HTTP, SMTP, POP3, FTP...
- Chúng ta s nghiên c u chi ti t các giao th c này chương 3
9
CHƯƠNG 2: L P TRÌNH M NG TRONG .NET FRAMEWORK
2.1. Socket hư ng k t n i (TCP Socket)
Socket là m t giao di n l p trình ng d ng (API) m ng
Thông qua giao di n này chúng ta có th l p trình ñi u khi n vi c truy n thông gi a
hai máy s d ng các giao th c m c th p là TCP, UDP…
Socket là s tr u tư ng hoá m c cao, có th tư ng tư ng nó như là thi t b truy n
thông hai chi u g i – nh n d li u gi a hai máy tính v i nhau.
Các lo i Socket
Socket hư ng k t n i (TCP Socket)
Socket không hư ng k t n i (UDP Socket)
Raw Socket
ð c ñi m c a Socket hư ng k t n i
Có 1 ñư ng k t n i o gi a 2 ti n trình
M t trong 2 ti n trình ph i ñ i ti n trình kia yêu c u k t n i.
Có th s d ng ñ liên l c theo mô hình Client/Server
Trong mô hình Client/Server thì Server l ng nghe và ch p nh n m t yêu
c u k t n i
M i thông ñi p g i ñ u có xác nh n tr v
Các gói tin chuy n ñi tu n t
ð c ñi m c a Socket không hư ng k t n i
Hai ti n trình liên l c v i nhau không k t n i tr c ti p
Thông ñi p g i ñi ph i kèm theo ñ a ch c a ngư i nh n
Thông ñi p có th g i nhi u l n
Ngư i g i không ch c ch n thông ñi p t i tay ngư i nh n
Thông ñi p g i sau có th ñ n ñích trư c thông ñi p g i trư c ñó.
S hi u c ng c a Socket
10
ð có th th c hi n các cu c giao ti p, m t trong hai quá trình ph i công
b s hi u c ng c a socket mà mình s d ng.
M i c ng giao ti p th hi n m t ñ a ch xác ñ nh trong h th ng. Khi quá
trình ñư c gán m t s hi u c ng, nó có th nh n d li u g i ñ n c ng
này t các quá trình khác.
Quá trình còn l i cũng yêu c u t o ra m t socket.
2.1.1. Gi i thi u v NameSpace System.Net và System.Net.Sockets
Cung c p m t giao di n l p trình ñơn gi n cho r t nhi u các giao th c m ng.
Có r t nhi u l p ñ l p trình
Ta quan tâm l p IPAdress, IPEndPoint, DNS, …
L p IPAdress
M t s Field c n chú ý:
Any: Cung c p m t ñ a ch IP ñ ch ra r ng Server ph i l ng nghe trên
t t c các Card m ng
Broadcast: Cung c p m t ñ a ch IP qu ng bá
Loopback: Tr v m t ñ a ch IP l p
AdressFamily: Tr v h ñ a ch c a IP hi n hành
L p IPAddress
M t s phương th c c n chú ý:
Phương th c kh i t o
IPAddress(Byte[])
IPAddress(Int64)
IsLoopback: Cho bi t ñ a ch có ph i ñ a ch l p không
Parse: Chuy n IP d ng xâu v IP chu n
ToString: Tr ñ a ch IP v d ng xâu
TryParse: Ki m tra IP d ng xâu có h p l không?
L p IPEndPoint
M t s phương th c c n chú ý:
Phương th c kh i t o
IPEndPoint (Int64, Int32)
IPEndPoint (IPAddress, Int32)
Create: T o m t EndPoint t m t ñ a ch Socket
ToString : Tr v ñ a ch IP và s hi u c ng theo khuôn d ng ð aCh :
C ng, ví d : 192.168.1.1:8080
L p DNS
M t s thành ph n c a l p:
HostName: Cho bi t tên c a máy ñư c phân gi i
GetHostAddress: Tr v t t c IP c a m t tr m
GetHostEntry: Gi i ñáp tên ho c ñ a ch truy n vào và tr v ñ i tư ng
IPHostEntry
11
GetHostName: L y v tên c a máy tính c c b
NameSpace System.Net.Sockets
M t s l p hay dùng: TcpClient, UdpClient, TcpListener, Socket,
NetworkStream, …
ð t o ra Socket
Socket(AddressFamily af, SocketType st, ProtocolType pt)
SocketType Protocoltype Description
Dgram Udp Connectionless communication
Stream Tcp Connection-oriented
communication
Raw Icmp Internet Control Message
Protocol
Raw Raw 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. Vi t chương trình cho phía máy ch
Vi t chương trình cho phía máy ch
T o m t Socket
Liên k t v i m t IPEndPoint c c b
L ng nghe k t n i
Ch p nh n k t n i
G i nh n d li u theo giao th c ñã thi t k
12
ðóng k t n i sau khi ñã hoàn thành và tr l i tr ng thái l ng nghe ch
k t n i m i
Vi t chương trình cho phía máy ch
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
Socket newsock = Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Socket client = newsock.Accept();
//G i nh n d li u theo giao th c ñã thi t k
……….
newsock.Close();
Chương trình Server:
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];
13
data = Encoding.ASCII.GetBytes(s);
client.Send(data, data.Length, SocketFlags.None);
}
client.Shutdown(SocketShutdown.Both);
client.Close();
server.Close();
}
}
2.1.3. Vi t chương trình cho phía máy khách
Vi t chương trình cho phía máy khách
Xác ñ nh ñ a ch c a Server
T o Socket
K t n i ñ n Server
G i nh n d li u theo giao th c ñã thi t k
ðóng Socket
Vi t chương trình cho phía máy khách
IPEndPoint ipep = new IPEndPoint(Ipaddress.Parse("192.168.1.6"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,
ProtocolType.Tcp);
server.Connect(ipep);
Chương trình Client:
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);
14
s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Server gui:{0}", s);
}
client.Disconnect(true);
client.Close();
}
}
2.1.4. S d ng các lu ng nh p xu t v i Socket
T Socket ta có th t o ra lu ng ñ nh p xu t v i Socket ñó là s d ng l p
NetworkStream
Property Description
CanRead Is true if the NetworkStream supports reading
CanSeek Is always false for NetworkStreams
CanWrite Is true if the NetworkStream supports writing
DataAvailable Is true if there is data available to be read
Ví d chương trình Client/Server s d ng NetworkStream ñ g i và nh n d li u
Chương trình Client s d ng NetworkStream:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
15
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();
}
}
Chương trình Server s d ng 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);
}
16
client.Close();
server.Close();
}
}
Trên c s c a NetworkStream ta có th n i thêm các lu ng ñ nh p xu t theo hư ng
ký t như StreamReader, StreamWriter
Sau ñây là m t ví d v chương trình Client/Server s d ng lu ng nh p xu t, chương
trình Server chép phép Client g i lên yêu c u, n u yêu c u là GetDate không phân bi t
ch hoa ch thư ng thì Server tr v cho Client ngày hi n t i, n u yêu c u là GetTime
không phan bi t hoa thư ng thì Server tr v gi hi n t i, n u là Quit thì Server ng t
k t n i v i Client, không ph i các trư ng h p trên thì thông báo không hi u lênh.
Chương trình phía 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();
}
}
Chương trình phía Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
17
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 không hư ng k t n i (UDP Socket)
Chương trình phía máy ch
T o m t Socket
Liên k t v i m t IPEndPoint c c b
G i nh n d li u theo giao th c ñã thi t k
ðóng Socket
Chương trình phía máy khách
Xác ñ nh ñ a ch Server
T o Socket
G i nh n d li u theo giao th c ñã thi t k
ðóng Socket
2.2.1. Vi t chương trình cho phía máy ch
using System;
18
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. Vi t chương trình cho phía máy khách
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;
19
data = new byte[1024];
int recv = client.ReceiveFrom(data, ref remote);
s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine("Nhan ve tu Server{0}",s);
while (true) {
s = Console.ReadLine();
data=new byte[1024];
data = Encoding.ASCII.GetBytes(s);
client.SendTo(data, remote);
if (s.ToUpper().Equals("QUIT")) break;
data = new byte[1024];
recv = client.ReceiveFrom(data, ref remote);
s = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(s);
}
client.Close();
}
}
S d ng Socket không hư ng k t n i vi t chương trình chat giưa 2 máy như
sau: (Sau này chúng ta có th s d ng l p UdpClient)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public partial class Form1 : Form {
private Socket udp1;
private IPEndPoint ipremote, iplocal;
public Form1() {
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void btStart_Click(object sender, EventArgs e) {
udp1 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
iplocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"),
int.Parse(txtLocalPort.Text));
udp1.Bind(iplocal);
ipremote = new IPEndPoint(IPAddress.Parse(txtIp.Text),
int.Parse(txtRemotePort.Text));
Thread tuyen = new Thread(new ThreadStart(NhanDL));
tuyen.Start();
20
}
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 + "rn";
}
}
private void button1_Click(object sender, EventArgs e) {
MessageBox.Show(txtSend.Text.Substring(0, txtSend.Text.IndexOf(" ")));
}
}
2.2.3. S d ng l p System.IO.MemoryStream ñ t o vùng ñ m nh p xu t
2.3. S d ng các l p h tr ñư c xây d ng t l p Soket
21
2.3.1. L p TCPClient
M c ñích c a l p UDPClient trên là dùng cho l p trình v i giao th c UDP,
v i giao th c này thì hai bên không c n ph i thi t l p k t n i trư c khi g i do v y m c
ñ tin c y không cao. ð ñ m b o ñ tin c y trong các ng d ng m ng, ngư i ta còn
dùng m t giao th c khác, g i là giao th c có k t n i : TCP (Transport Control
Protocol). Trên Internet ch y u là dùng lo i giao th c này, ví d như Telnet, HTTP,
SMTP, POP3… ð l p trình theo giao th c TCP, MS.NET cung c p hai l p có tên là
TCPClient và TCPListener.
- Các thành ph n c a l p TcpClient
+ Phương th c kh i t o:
Constructor Method
Name Description
TcpClient ()
T o m t ñ i tư ng TcpClient. Chưa ñ t thông s gì.
TcpClient
(IPEndPoint)
T o m t TcpClient và g n cho nó m t EndPoint c c b .
(Gán ñ a ch máy c c b và s hi u c ng ñ s d ng trao
ñ i thông tin v sau)
TcpClient
(RemoteHost: String,
Int32)
T o m t ñ i tư ng TcpClient và k t n i ñ n m t máy có
ñ a ch và s hi u c ng ñư c truy n vào.. RemoteHost có
th là ñ a ch IP chu n ho c tên máy.
+ M t s thu c tính:
Name Description
Available Cho bi t s byte ñã nh n v t m ng và có s n
ñ ñ c.
Client Tr v Socket ng v i TCPClient hi n hành.
Connected Tr ng thái cho bi t ñã k t n i ñư c ñ n Server hay chưa ?
+ M t s phương th c:
Name Description
Close Gi i phóng ñ i tư ng TcpClient nhưng
không ñóng k t n i.
Connect
(RemoteHost,
Port)
K t n i ñ n m t máy TCP khác có Tên và
s hi u c ng.
22
GetStream Tr v NetworkStream ñ t ñó giúp ta
g i hay nh n d li u. (Thư ng làm tham
s khi t o StreamReader và
StreamWriter) .
Khi ñã g n vào StreamReader và
StreamWriter r i thì ta có th g i và nh n
d li u thông qua các phương th c
Readln, writeline tương ng c a các l p
này.
Ta s d ng l p TcpClient vi t l i chương trình DateTimeClient như sau:
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);
TcpClient client = new TcpClient();
client.Connect(iep);
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());
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();
client.Close();
}
}
2.3.2. L p TCPListener
TCPListerner là m t l p cho phép ngư i l p trình có th xây d ng các ng
d ng Server (Ví d như SMTP Server, FTP Server, DNS Server, POP3 Server hay
server t ñ nh nghĩa ….). ng d ng server khác v i ng d ng Client ch nó luôn
luôn th c hi n l ng nghe và ch p nh n các k t n i ñ n t Client.
23
Các thành ph n c a l p TcpListener:
+ Phương th c kh i t o:
Constructor method
Name Description
TcpListener (Port:
Int32)
T o m t TcpListener và l ng nghe t i c ng ch ñ nh.
TcpListener
(IPEndPoint)
T o m t TcpListener v i giá tr Endpoint truy n vào.
TcpListener
(IPAddress, Int32)
T o m t TcpListener và l ng nghe các k t n i ñ n t i
ñ a ch IP và c ng ch ñ nh.
+ Các phương th c khác
Name Description
AcceptSocket Ch p nh n m t yêu c u k t n i ñang ch .
AcceptTcpClient Ch p nh n m t yêu c u k t n i ñang ch . ( ng d ng s
d ng t i l nh này cho ñ n khi nào có m t k t n i ñ n)
Pending Cho bi t li u có k t n i nào ñang ch ñ i không ? (True
= có).
Start B t ñ u l ng nghe các yêu c u k t n i.
Stop D ng vi c nghe.
S d ng l p TcpListener ta vi t l i chương trình DateTime Server như sau:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
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);
TcpListener server = new TcpListener(iep);
server.Start();
TcpClient client = server.AcceptTcpClient();
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw = new StreamWriter(client.GetStream());
string kq="";
while (true) {
24
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. L p UDPClient
Giao thøc UDP (User Datagram Protocol hay User Define Protocol) l mét giao thøc
phi kÕt nèi (Connectionless) cã nghÜa l mét bªn cã thÓ göi d÷ liÖu cho bªn kia m kh«ng cÇn
biÕt l bªn ®ã ® s½n s ng hay ch−a ? (Nãi c¸ch kh¸c l kh«ng cÇn thiÕt lËp kÕt nèi gi÷a hai
bªn khi tiÕn h nh trao ®æi th«ng tin). Giao thøc n y kh«ng tin cËy b»ng giao thøc TCP nh−ng
tèc ®é l¹i nhanh v dÔ c i ®Æt. Ngo i ra, víi giao thøc UDP ta cßn cã thÓ göi c¸c gãi tin qu¶ng
b¸ (Broadcast) cho ®ång thêi nhiÒu m¸y.
Trong .NET, líp UDPClient (n»m trong System.Net.Sockets) ®ãng gãi c¸c chøc n¨ng
cña giao thøc UDP.
Constructor methosd Description
UdpClient ()
T¹o mét ®èi t−îng (thÓ hiÖn) míi cña líp
UDPClient.
UdpClient (AddressFamily)
T¹o mét ®èi t−îng (thÓ hiÖn) míi cña líp
UDPClient. Thuéc mét dßng ®Þa chØ
(AddressFamily) ®−îc chØ ®Þnh.
UdpClient (Int32)
T¹o mét UdpClient v g¾n (bind) mét cæng cho nã.
UdpClient (IPEndPoint)
T¹o mét UdpClient v g¾n (bind) mét IPEndpoint
(g¸n ®Þa chØ IP v cæng) cho nã.
UdpClient (Int32, AddressFamily)
T¹o mét UdpClient v g¸n sè hiÖu cæng,
AddressFamily
25
UdpClient (String, Int32)
T¹o mét UdpClient v thiÕt lËp víi mét tr¹m tõ xa
mÆc ®Þnh.
PUBLIC Method
Name Description
BeginReceive NhËn d÷ liÖu Kh«ng ®ång bé tõ m¸y ë xa.
BeginSend Göi kh«ng ®ång bé d÷ liÖu tíi m¸y ë xa
Close §ãng kÕt nèi.
Connect ThiÕt lËp mét Default remote host.
EndReceive KÕt thóc nhËn d÷ liÖu kh«ng ®ång bé ë trªn
EndSend KÕt thóc viÖc göi d÷ liÖu kh«ng ®ång bé ë trªn
Receive NhËn d÷ liÖu (®ång bé) do m¸y ë xa göi. (§ång bé cã
nghÜa l c¸c lÖnh ngay sau lÖnh Receive chØ ®−îc thùc thi nÕu
Receive ® nhËn ®−îc d÷ liÖu vÒ . Cßn nÕu nã ch−a nhËn
®−îc – dï chØ mét chót – th× nã vÉn cø chê (blocking))
Send Göi d÷ liÖu (®ång bé) cho m¸y ë xa.
Ví d s d ng UdpClient vi t chương trình Chat gi a 2 máy:
Do chương trình 2 máy là như nhau ta ch c n vi t m t chương trình copy ra ñ s
d ng.
Hình nh c a nó như sau:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
26
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 + "rn";
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 + "rn";
}
}
}
}
2.4. Socket không ñ ng b
2.4.1. Mô hình x lý s ki n c a windows
27
Mô hình x lý s ki n c a Windows ñư c th hi n qua hình sau:
Như v y thông qua mô hình này ta có th y nhi m cho m t th t c nào ñó th c
hi n khi s ki n s y ra trên các Control
Ví d :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace EventDemo {
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
button1.Click += new EventHandler(NhanTiep);
}
private void button1_Click(object sender, EventArgs e) {
MessageBox.Show("Bac da nhan em");
}
private void NhanTiep(object sender, EventArgs e) {
MessageBox.Show("Bac lai nhan em roi");
}
}
}
ví d trên chúng ta ngoài s ki n Click c a button 1 chúng ta thêm m t x
ki n khi button1 ñư c nh n ñó là s ki n NhanTiep.
2.4.2. S d ng Socket không ñ ng b
ð l p trình không ñ ng b v i Socket chúng ta s d ng các phương th c cho
vi c s d ng b t ñ ng b
28
Các phương th c cho vi c l p trình b t ñ ng b ñư c chia làm 2 l i thư ng b t
ñ u b ng Begin và End:
Phương th c b t ñ u b ng Begin, b t ñ u m t ch c năng và ñư c ñăng
ký v i phương th c AsyncCallback
B t ñ u b ng End ch ch c năng hoàn thành khi AsyncCallback ñư c
g i.
EndSendTo()To send data to a
specific remote host
BeginSendTo()
EndSend()To send data from a
socket
BeginSend()
EndReceiveFrom()To retrieve data from a
specific remote host
BeginReceiveFrom()
EndReceive()To retrieve data from a
socket
BeginReceive()
EndConnect()To connect to a remote
host
BeginConnect()
EndAccept()To accept an incoming
connection
BeginAccept()
Requests Ended BY…Description of RequestRequests Started By…
EndSendTo()To send data to a
specific remote host
BeginSendTo()
EndSend()To send data from a
socket
BeginSend()
EndReceiveFrom()To retrieve data from a
specific remote host
BeginReceiveFrom()
EndReceive()To retrieve data from a
socket
BeginReceive()
EndConnect()To connect to a remote
host
BeginConnect()
EndAccept()To accept an incoming
connection
BeginAccept()
Requests Ended BY…Description of RequestRequests Started By…
- ð ch p nh n k t n i b t ñ ng b ta s d ng phương th c BeginAccept() và
EndAccept() như sau:
Phương th c BeginAccept() và EndAccept()
IAsyncResult BeginAccept(AsyncCallback callback, object state)
Socket EndAccept(IAsyncResult iar);
Thư ng ñư c dùng như sau:
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep);
sock.Listen(5);
sock.BeginAccept(new AsyncCallback(CallAccept), sock);
Trong ñó phương th c CallAccept thư ng ñư c vi t như sau:
private static void CallAccept(IAsyncResult iar) {
Socket server = (Socket)iar.AsyncState;
Socket client = server.EndAccept(iar);
. . .
}
- ð thi t l p k t n i theo cách b t ñ ng b chúng ta s d ng phương th c
BeginConnect() và EndConnect() như sau:
Phương th c BeginConnect() và EndConnect()
29
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep =new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
Trong ñó phương th c Connected thư ng ñư c vi t như sau:
public static void Connected(IAsyncResult iar) {
Socket sock = (Socket)iar.AsyncState;
try {
sock.EndConnect(iar);
} catch (SocketException) {
Console.WriteLine("Unable to connect to host");
}
}
- ð g i d li u b t ñ ng b chúng ta làm như sau:
+ Phương th c BeginSend() và EndSend()
+ BeginSend()
IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags sockflag,
AsyncCallback callback, object state)
Ví d :
sock.BeginSend(data, 0, data.Length, SocketFlags.None, new
AsyncCallback(SendData), sock);
+ EndSend()
int EndSend(IAsyncResult iar)
Trong ñó phương th c SendData thư ng ñư c vi t như sau:
private static void SendData(IAsyncResult iar) {
Socket server = (Socket)iar.AsyncState;
int sent = server.EndSend(iar);
}
Tương t như giao th c hư ng k t n i n u ta s d ng g i d li u theo giao th c
không hư ng k t n i chúng ta cũng th c hi n tương t như sau:
Phương th c BeginSendTo() và EndSendTo()
IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags
sockflag, EndPoint ep, AsyncCallback callback, object state)
Ví d :
IPEndPoint iep = new EndPoint(IPAddress.Parse("192.168.1.6"), 9050);
sock.BeginSendTo(data, 0, data.Length, SocketFlags.None, iep, new
AsynCallback(SendDataTo), sock);
int EndSendTo(IAsyncResult iar)
- ð nh n d li u b t ñ ng b ta th c hi n như sau:
+ Nh n d li u v i giao th c hư ng k t n i:
Phương th c BeginReceive và EndReceive()
30
sock.BeginReceive(data, 0, data.Length, SocketFlags.None, new
AsyncCallback(ReceivedData), sock);
V i ReceivedData ñư c ñ nh nghĩa như sau:
void ReceivedData(IAsyncResult iar) {
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceive(iar);
string receivedData = Encoding.ASCII.GetString(data, 0,
recv);
Console.WriteLine(receivedData);
}
+ Nh n d li u b t ñ ng b v i giao th c không hư ng k t n i.
Phương th c BeginReceiveFrom() and EndReceiveFrom()
sock.BeginReceive(data, 0, data.Length, SocketFlags.None, ref iep, new
AsyncCallback(ReceiveData), sock);
void ReceiveData(IasyncResult iar){
Socket remote = (Socket)iar.AsyncState;
int recv = remote.EndReceiveFrom(iar);
string stringData = Encoding.ASCII.GetString(data, 0,
recv);
Console.WriteLine(stringData);
}
2.4.3. Ví d v Socket không ñ ng b
Sau ñây chúng ta s s d ng các phương th c không ñ ng b vi t chương trình
Client/Server theo Socket b t ñ ng b , m i khi Client g i d li u lên Server, nó s in
ra và g i tr l i cho Client. Mô hình c a client/server s d ng các phương th c b t
ñ ng b như sau:
31
Chương trình phía Client:
using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
class AsyncTcpClient:Form
{
private TextBox newText;
private TextBox conStatus;
private ListBox results;
private Socket client;
private byte[] data = new byte[1024];
private int size = 1024;
public AsyncTcpClient()
{
Text = "Asynchronous TCP Client";
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);
Label label2 = new Label();
label2.Parent = this;
32
label2.Text = "Connection Status:";
label2.AutoSize = true;
label2.Location = new Point(10, 330);
conStatus = new TextBox();
conStatus.Parent = this;
conStatus.Text = "Disconnected";
conStatus.Size = new Size(200, 2 * Font.Height);
conStatus.Location = new Point(110, 325);
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 discon = new Button();
discon.Parent = this;
discon.Text = "Disconnect";
discon.Location = new Point(295,52);
discon.Size = new Size(6 * Font.Height, 2 * Font.Height);
discon.Click += new EventHandler(ButtonDisconOnClick);
}
void ButtonConnectOnClick(object obj, EventArgs ea)
{
conStatus.Text = "Connecting...";
Socket newsock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);
}
void ButtonSendOnClick(object obj, EventArgs ea)
{
byte[] message = Encoding.ASCII.GetBytes(newText.Text);
newText.Clear();
client.BeginSend(message, 0, message.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
void ButtonDisconOnClick(object obj, EventArgs ea)
{
client.Close();
conStatus.Text = "Disconnected";
}
void Connected(IAsyncResult iar)
{
33
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());
}
}
Chương trình phía 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);
34
results = new ListBox();
results.Parent = this;
results.Location = new Point(10, 65);
results.Size = new Size(350, 20 * Font.Height);
Label label1 = new Label();
label1.Parent = this;
label1.Text = "Text received from client:";
label1.AutoSize = true;
label1.Location = new Point(10, 45);
Label label2 = new Label();
label2.Parent = this;
label2.Text = "Connection Status:";
label2.AutoSize = true;
label2.Location = new Point(10, 330);
conStatus = new TextBox();
conStatus.Parent = this;
conStatus.Text = "Waiting for client...";
conStatus.Size = new Size(200, 2 * Font.Height);
conStatus.Location = new Point(110, 325);
Button stopServer = new Button();
stopServer.Parent = this;
stopServer.Text = "Stop Server";
stopServer.Location = new Point(260,32);
stopServer.Size = new Size(7 * Font.Height, 2 * Font.Height);
stopServer.Click += new EventHandler(ButtonStopOnClick);
server = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
server.Bind(iep);
server.Listen(5);
server.BeginAccept(new AsyncCallback(AcceptConn), server);
}
void ButtonStopOnClick(object obj, EventArgs ea)
{
Close();
}
void AcceptConn(IAsyncResult iar)
{
Socket oldserver = (Socket)iar.AsyncState;
Socket client = oldserver.EndAccept(iar);
conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString();
string stringData = "Welcome to my server";
byte[] message1 = Encoding.ASCII.GetBytes(stringData);
client.BeginSend(message1, 0, message1.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
void SendData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
35
int sent = client.EndSend(iar);
client.BeginReceive(data, 0, size, SocketFlags.None,
new AsyncCallback(ReceiveData), client);
}
void ReceiveData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int recv = client.EndReceive(iar);
if (recv == 0)
{
client.Close();
conStatus.Text = "Waiting for client...";
server.BeginAccept(new AsyncCallback(AcceptConn), server);
return;
}
string receivedData = Encoding.ASCII.GetString(data, 0, recv);
results.Items.Add(receivedData);
byte[] message2 = Encoding.ASCII.GetBytes(receivedData);
client.BeginSend(message2, 0, message2.Length, SocketFlags.None,
new AsyncCallback(SendData), client);
}
public static void Main()
{
Application.Run(new AsyncTcpSrvr());
}
}
2.4.4. S d ng các phương th c Non-blocking
ð l p trình b t ñ ng b chúng ta có th s d ng các phương th c Non –
bloking như phương th c Poll() và phương th c Select:
+ Phương th c Poll()
bool Poll(int microseconds, SelectMode mode);
SelectRead: Poll() tr v true n u m t trong nh ng ñi u ki n sau ñư c
tho :
N u phương th c Accept() thành công
N u có d li u trên Socket
N u k t n i ñã ñóng
SelectWrite: Poll() tr v true n u tho m t trong nh ng ñi u ki n sau:
Phương th c Connect() thành công
N u có d li u trên Socket ñ g i
SelectError: Poll() tr v true n u m t trong nh ng ñi u ki n sau ñư c
tho :
N u phương th c Connect() th t b i
N u có d li u ngoài băng thông chu n g i ñ n nhưng thu c tính
OutOfBandInline không ñư c thi t l p là true.
+ Phương th c Select():
36
Socket.Select(IList checkRead, IList checkWrite, IList checkError, int
microseconds)
• checkRead monitors the specified sockets for the ability to read data from the
socket.
• checkWrite monitors the specified sockets for the ability to write data to the
socket.
• checkError monitors the specified sockets for error conditions.
Ví d ng d ng Server s d ng phương th c Poll()
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class TcpPollSrvr
{
public static void Main()
{
int recv;
byte[] data = new byte[1024];
IPEndPoint ipep = new IPEndPoint(IPAddress.Any,
9050);
Socket newsock = new
Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);
newsock.Listen(10);
Console.WriteLine("Waiting for a client...");
bool result;
int i = 0;
while (true)
{
i++;
Console.WriteLine("polling for accept#{0}...", i);
result = newsock.Poll(1000000, SelectMode.SelectRead);
if (result)
{
break;
}
}
Socket client = newsock.Accept();
IPEndPoint newclient =
(IPEndPoint)client.RemoteEndPoint;
Console.WriteLine("Connected with {0} at port {1}",
newclient.Address, newclient.Port);
string welcome = "Welcome to my test server";
data = Encoding.ASCII.GetBytes(welcome);
client.Send(data, data.Length,
SocketFlags.None);
37
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 chúng ta s vi t m t chương trình Server s d ng phương th c Select()
ñ ch p nh n 2 k t n i ñ n t client và x lý t ng k t n i.
Chương trình 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;
38
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);
39
}
}
}
}
Chương trình 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 d ng Thread trong các ng d ng m ng
40
M t s khái ni m
- ða nhi m (Multitasking): Là kh năng h ñiêu hành làm nhi u công vi c t i m t th i
ñi m
- Ti n trình (Process): Khi ch y m t ng d ng, h ñi u hành s c p phát riêng cho ng
d ng ñó b nh và các tài nguyên khác. B nh và tài nguyên v t lý riêng bi t này
ñư c g i là m t ti n trình. Các tài nguyên và b nh c a m t ti n trình thì ch ti n
trình ñó ñư c phép truy c p.
- Tuy n (Thread): Trong h th ng, m t ti n trình có th có m t ho c nhi u chu i th c
hi n tách bi t nhau và có th ch y ñ ng th i. M i chu i th c hi n này ñư c g i là m t
tuy n (Thread). Trong m t ng d ng, Thread kh i t o ñ u tiên g i là Thread sơ c p
hay Thread chính.
2.5.1. S d ng Thread trong chương trình .Net
ð s d ng Thread trong .Net ta s d ng NameSpace System.Threading
- M t s phương th c thư ng dùng
Public Method
Name
Mô t
Abort() K t thúc Thread
Join() Bu c chương trình ph i ch cho thread k t thúc (Block) thì m i th c hi n
ti p (các câu l nh ñ ng sau Join).
Resume() Ti p t c ch y thread ñã b t m ngưng - suspended.
Sleep() Static method : T m d ng thread trong m t kho ng th i gian.
Start() B t ñ u ch y (kh i ñ ng) m t thread. Sau khi g i phương th c này, tr ng
thái c a thread chuy n t tr ng thái hi n hành sang Running.
Suspend() T m ngưng (ngh ) thread. (Phương th c này ñã b lo i kh i phiên b n
VS.NET 2005)
- M t s thu c tính thư ng dùng:
Public Property
Name
Mô t
CurrentThread This static property: Tr v thread hi n hành ñang ch y.
IsAlive Tr v giá tr cho bi t tr ng thái th c thi c a thread hi n hành.
IsBackground Sets or gets giá tr cho bi t là thread là background hay foreground
thread.
IsThreadPoolThread Gets a value indicating whether a thread is part of a thread pool.
Priority Sets or gets giá tr ñ ch ñ nh ñ ưu tiên (dành nhi u hay ít CPU cho
thread). Cao nh t là 4, th p nh t là 0.
41
Public Property
Name
Mô t
ThreadState L y v tr ng thái c a thread (ñang d ng, hay ñang ch y…)
- T o m t tuy n trong C#
……
Thread newThread=newThread(new ThreadStart(newMethod));
…….
}
void newMethod() {
. . .
}
2.5.2. S d ng Thread trong các chương trình Server
- ða tuyên hay ñư c ng d ng trong các chương trình Server, các chương trình
ñòi h i t i m t th i ñi m ch p nh n nhi u k t n i ñ n t các Client.
- ð các chương trình Server có th x lý nhi u Client t i m t th i ñi m ta có
mô hình ng d ng ña tuy n như sau:
Sau ñây chúng ta vi t l i chương trình DateTimeServer có s d ng Thread như sau:
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) {
42
//chap nhan ket noi
TcpClient client= server.AcceptTcpClient();
//Tao ra tuyen moi de xu ly moi Client
new ClientThread(client);
}
server.Stop();
}
}
class ClientThread {
private Thread tuyen;
private TcpClient client;
public ClientThread(TcpClient client) {
this.client = client;
tuyen = new Thread(new ThreadStart(GuiNhanDL));
tuyen.Start();
}
private void GuiNhanDL() {
StreamReader sr = new StreamReader(client.GetStream());
StreamWriter sw= new StreamWriter(client.GetStream());
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();
}
client.Close();
}
}
2.5.3. S d ng Thread ñ g i/nh n d li u
ng d ng ña tuy n trong vi c g i nh n d li u chúng ta vi t chương trình Chat
theo giao th c TCP như sau:
43
ng d ng mô hình x lý s ki n c a Windows và ña tuy n và Socket không
ñ ng b ta ch c n vi t m t chương trình sau ñó d ch ra, ta ch y ng d ng nh n Listen
nó s l ng nghe trong vai trò Server còn khi ta ch y và nh n Connect nó s ñóng vai
trò Client và k t n i t i Server.
Văn b n chương trình như sau:
using System;
using System.Drawing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
44
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);
46
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 d ng ThreadPool trong các chương trình .Net
Method Description
BindHandle() Binds an operating system handle to the
thread pool
GetAvailableThreads() Gets the number of worker threads
available for use in the thread pool
GetMaxThreads() Gets the maximum number of worker
threads available in the thread pool
QueueUserWorkItem() Queues a user delegate to the thread
pool
RegisterWaitForSingleObject() Registers a delegate waiting for a
WaitHandle object
UnsafeQueueUserWorkItem() Queues an unsafe user delegate to the
thread pool but does not propagate the
calling stack onto the worker thread
UnsafeRegisterWaitForSingleObject() Registers an unsafe delegate waiting for
a WaitHandle object
using System;
using System.Threading;
class ThreadPoolSample
{
47
public static void Main()
{
ThreadPoolSample tps = new ThreadPoolSample();
}
public ThreadPoolSample()
{
int i;
ThreadPool.QueueUserWorkItem(new WaitCallback(Counter));
ThreadPool.QueueUserWorkItem(new WaitCallback(Counter2));
for(i = 0; i < 10; i++)
{
Console.WriteLine("main: {0}", i);
Thread.Sleep(1000);
}
}
void Counter(object state)
{
int i;
for (i = 0; i < 10; i++)
{
Console.WriteLine(" thread: {0}", i);
Thread.Sleep(2000);
}
}
void Counter2(object state)
{
int i;
for (i = 0; i < 10; i++)
{
Console.WriteLine(" thread2: {0}", i);
Thread.Sleep(3000);
}
}
}
2.5.5. S d ng ThreadPool trong các chương trình Server
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
class ThreadPoolTcpSrvr
{
private TcpListener client;
public ThreadPoolTcpSrvr()
{
client = new TcpListener(9050);
client.Start();
Console.WriteLine("Waiting for clients...");
while(true)
{
while (!client.Pending())
{
Thread.Sleep(1000);
}
ConnectionThread newconnection = new ConnectionThread();
newconnection.threadListener = this.client;
ThreadPool.QueueUserWorkItem(new
WaitCallback(newconnection.HandleConnection));
}
}
public static void Main()
{
ThreadPoolTcpSrvr tpts = new ThreadPoolTcpSrvr();
48
}
}
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. K thu t IP Multicasting
2.6.1. Broadcasting là gì?
Broadcast, ti ng Vi t g i là qu ng bá. Trong h th ng m ng h u tuy n, qu ng bá là
thu t ng dùng ñ ch vi c g i m t gói thông tin ñ n t t các nút m ng trong m ng. ð
th c hi n hình th c qu ng bá, ñ a ch ñ n c a gói tin s là ñ a ch qu ng bá.
Có hai lo i là: Local Broadcast và Global Broadcast
2.6.2. S d ng Broadcasting ñ g i d li u ñ n nhi u máy trong m ng c c b
G i gói d li u 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();
}
49
}
Chúng ta ph i thi t l p 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();
}
}
Nh n gói d li u 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ì?
M t ñ a ch multicast cho phép thi t b g i d li u t i m t t p xác ñ nh trư c các host,
ñư c bi t ñ n như các nhóm multicast, trong các m ng con khác nhau.
M t s ñ a ch Multicast
ð a ch multicast Ch c năng
224.0.0.0 ð a ch cơ s
224.0.0.1 T t c các h th ng trên m ng con này
224.0.0.2 T t c các Router trên m ng con này
50
224.0.0.5 Các DR trong OSPF
224.0.1.9 Nhóm ñ a ch RIPv2
224.0.1.24 Nhóm ñ a ch WINS server
Có 2 k thu t Multicast ñư c s d ng
+ Peer to Peer
+ Central Server
2.6.4. Socket Multicasting trong .Net
S d ng phương th c SetSocketOption()
51
Socket option có th ñư c s d ng ñ
Thêm m t Socket vào nhóm Multicast
Lo i m t Socket kh i nhóm Multicast
SetSocketOption(SocketOptionLevel,SocketOptionName, optionValue)
SocketOptionName
AddMembership
DropMembership
S d ng phương th c SetSocketOption()
Socket option có th ñư c s d ng ñ
optionValue là m t ñ i tư ng c a l p MulticastOption
MulticastOption(IPAddress) MulticastOption(IPAddress,IPAddress)
Ví d thêm m t Socket vào nhóm Multicast 224.100.0.1
sock.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.AddMembership, new
MulticastOption(IPAddress.Parse("224.100.0.1"));
G i d li u Multicast
class MultiSend{
public static void Main() {
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
server.SendTo(data, iep);
server.Close();
}
}
Nh n d li u Multicast
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();
}
}
52
G i d li u Multicast v i TTL
class NewMultiSend{
public static void Main() {
Socket server = new Socket(AddressFamily.InterNetwork,
SocketType.Dgram, ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051);
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
server.Bind(iep);
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
server.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.AddMembership,
new MulticastOption(IPAddress.Parse("224.100.0.1")));
server.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.MulticastTimeToLive, 50);
server.SendTo(data, iep2);
server.Close();
}
}
Multicast v i l p UdpClient
JoinMulticastGroup()
DropMulticastGroup()
JoinMulticastGroup() là phương th c overload
JoinMulticastGroup(IPAddress)
JoinMulticastGroup(IPAddress, int)
class UdpClientMultiSend{
public static void Main() {
UdpClient sock = new UdpClient();
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
byte[] data = Encoding.ASCII.GetBytes("This is a test message");
sock.Send(data, data.Length, iep);
sock.Close();
}
}
class UdpClientMultiRecv
{
public static void Main()
{
UdpClient sock = new UdpClient(9050);
Console.WriteLine("Ready to receive…");
sock.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
byte[] data = sock.Receive(ref iep);
string stringData = Encoding.ASCII.GetString(data, 0, data.Length);
Console.WriteLine("received: {0} from: {1}", stringData, iep.ToString());
sock.Close();
}
}
53
2.7 Bài t p áp d ng
class MulticastChat : Form{
TextBox newText;
ListBox results;
Socket sock;
Thread receiver;
IPEndPoint multiep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
public MulticastChat() {
Text = "Multicast 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 closeit = new Button();
closeit.Parent = this;
closeit.Text = "Close";
closeit.Location = new Point(290, 52);
closeit.Size = new Size(5 * Font.Height, 2 * Font.Height);
closeit.Click += new EventHandler(ButtonCloseOnClick);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
sock.Bind(iep);
sock.SetSocketOption(SocketOptionLevel.IP,
SocketOptionName.AddMembership,
55
CHƯƠNG 3: XÂY D NG NG D NG M NG
3.1. Giao th c ICMP
Gi i thi u giao th c ICMP (Internetwork Control Message Protocol)
- Giao th c ICMP ho t ñ ng trên layer 2 - Internetwork trong mô hình TCP/IP ho c
layer 3 - Network trong mô hình OSI
Cho phép ki m tra và xác ñ nh l i c a Layer 3 Internetwork trong mô hình TCP/IP
b ng cách ñ nh nghĩa ra các lo i thông ñi p có th s d ng ñ xác ñ nh xem m ng hi n
t i có th truy n ñư c gói tin hay không.
Trong th c t , ICMP c n các thành ph n c a m i gói tin IP ñ có th ho t ñ ng ñư c.
C u trúc c a gói tin IP và ICMP
+ Type: có th là m t query hay m t l i
+ Code: Xác ñ nh ñây là lo i query hay thông ñi p l i
+ Checksum: Ki m tra và s a l i cho d li u ICMP
+ Message: Tuỳ thu c vào Type và Code
3.1.1. S d ng Raw Socket
Gói tin ICMP không s d ng TCP ho c UDP nên chúng ta không th s d ng các l p
ñư c h tr như TcpClient hay UdpClient mà ph i s d ng m t Raw Socket
Mu n t o Raw Socket khi t o ra Socket b n s d ng SocketType.Raw, giao th c
ICMP
T o Raw Socket như sau
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw,
ProtocolType.Icmp);
Raw Socket Format
Value Description
Ggp Gateway-to-Gateway Protocol
Icmp Internet Control Message Protocol
56
Idp IDP Protocol
Igmp Internet Group Management Protocol
IP A raw IP packet
Ipx Novell IPX Protocol
ND Net Disk Protocol
Pup Xerox PARC Universal Protocol (PUP)
Raw A raw IP packet
Spx Novell SPX Protocol
SpxII Novell SPX Version 2 Protocol
Unknown An unknown protocol
Unspecified An unspecified protocol
G i gói d li u Raw
ICMP là giao th c không hư ng k t n i
S d ng phương th c SendTo() c a l p Socket ñ g i
C ng trong giao th c ICMP không quan tr ng
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 0);
sock.SendTo(packet, iep);
Nh n gói d li u Raw
S d ng phương th c ReceiveForm c a l p Socket
D li u nh n v là m t gói tin IP chúng ta ph i tách ra ñ l y gói tin ICMP
Raw Socket không t ñ ng ñ nh d ng gói tin ICMP cho chúng ta. Chúng ta ph i t làm
Data Variable Size Type
Type 1 byte Byte
Code 1 byte Byte
Checksum 2 bytes Unsigned 16-bit integer
Message multibyte Byte array
ð nh nghĩa l p và phương th c kh i t o m c ñ nh
class ICMP {
public byte Type;
public byte Code;
public UInt16 Checksum;
public int Messagesize;
public byte[] Message = new byte[1024];
public ICMP() {
}
}
T o ra gói tin ICMP
ICMP packet = new ICMP();
57
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 d ng giao th c ICMP và Raw Socket ñ xây d ng chương trình Ping
58
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);
59
int Sequence = BitConverter.ToInt16(response.Message, 2);
Console.WriteLine(" Identifier: {0}", Identifier);
Console.WriteLine(" Sequence: {0}", Sequence);
string stringData = Encoding.ASCII.GetString(response.Message, 4,
response.MessageSize - 4);
Console.WriteLine(" data: {0}", stringData);
host.Close();
}
}
3.1.3. S d ng giao th c ICMP và Raw Socket ñ xây d ng chương trình
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;
60
}
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 th c SMTP, POP3
3.2.1. Cơ b n v h th ng Mail và giao th c SMTP, POP3
61
* Giao th c SMTP
M t s l nh cơ b n c a giao th c SMTP:
L nh Mô t
HELO Hello. S d ng ñ xác ñ nh ngư i g i ñi n. L nh này này ñi
kèm v i tên c a host g i ñi n. Trong ESTMP (extended
protocol), thì l nh này s là EHLO.
MAIL Kh i t o m t giao d ch g i thư. Nó k t h p "from" ñ xác ñ nh
ngư i g i thư.
RCPT Xác ñ nh ngư i nh n thư.
DATA Thông báo b t ñ u n i dung th c s c a b c ñi n (ph n thân
c a thư). D li u ñư c mã thành d ng mã 128-bit ASCII và nó
ñư c k t thúc v i m t dòng ñơn ch a d u ch m (.).
RSET Hu b giao d ch thư
VRFY S d ng ñ xác th c ngư i nh n thư.
NOOP Nó là l nh "no operation" xác ñ nh không th c hi n hành
ñ ng gì
QUIT Thoát kh i ti n trình ñ k t thúc
SEND Cho host nh n bi t r ng thư còn ph i g i ñ n ñ u cu i khác.
M t s l nh không yêu c u ph i có ñư c xác ñ nh b ng RFC 821
SOMLSend or mail. Báo v i host nh n thư r ng thư ph i
g i ñ n ñ u cu i khác ho c h p thư.
SAML Send and mail. Nói v i host nh n r ng b c ñi n
ph i g i t i ngư i dùng ñ u cu i và h p thư.
EXPN S d ng m r ng cho m t mailing list.
HELP Yêu c u thông tin giúp ñ t ñ u nh n thư.
TURN Yêu c u ñ host nh n gi vai trò là host g i thư.
- Mã tr ng thái c a SMTP
Khi m t MTA g i m t l nh SMTP t i MTA nh n thì MTA nh n s tr l i v i
m t mã tr ng thái ñ cho ngư i g i bi t ñang có vi c gì x y ra ñ u nh n. Và dư i ñây
là b ng mã tr ng thái c a SMTP theo tiêu chu n RFC 821. M c ñ c a tr ng thái ñư c
62
xác ñ nh b i s ñ u tiên c a mã (5xx là l i n ng, 4xx là l i t m th i, 1xx–3xx là ho t
ñ ng bình thư ng).
- M t s mã tr ng thái c a SMTP
211 Tình tr ng h th ng, hay reply giúp ñ h th ng
214 Thông ñi p giúp ñ .
220 <domain> d ch v s n sàng
221 <domain> d ch v ñóng kênh giao chuy n
250 Hành ñ ng mail yêu c u OK, hoàn thành
251 User không c c b ; s hư ng ñ n <forward-path>
354 Kh i ñ ng vi c nh p mail; k t thúc v i <CLRF>. <CLRF>
421 <domain> d ch v không s d ng ñư c, ñóng kênh giao chuy n
450 Không l y hành ñ ng mail yêu c u; mailbox không hi u l c
451 Không nh n hành ñ ng ñư c yêu c u; lưu tr c a h th ng không ñ .
500 L i cú pháp; không ch p nh n l nh
501 L i cú pháp trong tham s hay ñ i s
502 L nh không ñư c cung c p
503 Dòng l nh sai
504 Tham s c a dòng l nh không ñư c cung c p
550 Không nh n hành ñ ng ñư c yêu c u ; mailbox không hi u l c
[như mailbox không tìm th y hay không truy c p ñư c]
551 User không c c b ; vui lòng th <forward-path>
552 B qua hành ñ ng mà mail yêu c u, vư t quá ch ñ nh lưu tr
554 Không nh n hành ñ ng ñư c yêu c u; tên mailbox không ñư c
ch p nh n. [như sai cú pháp mailbox] giao chuy n sai.
- ð nh d ng c a m t b c thư thông thư ng không có ph n ñính kèm như sau:
* Giao th c POP3
Giao th c dùng ñ l y thư, POP3 Server l ng nghe trên c ng 110, mô t trong
RFC 1939
63
- M t s l nh c a POP3
USER Xác ñ nh username
PASS Xác ñ nh password
STAT Yêu c u v tr ng thái c a h p thư như s lư ng thư và ñ l n c a thư
LIST Hi n danh sách c a thư
RETR Nh n thư
DELE Xoá m t b c thư xác ñ nh
NOOPKhông làm gì c
RSET Khôi ph c l i như thư ñã xoá (rollback)
QUIT Th c hi n vi c thay ñ i và thoát ra
3.2.2. Cài ñ t SMTP, POP3 Client/Server
Vi t chương trình g i Mail ñơn gi n theo giao th c 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());
64
//Gui dia chi nguyoi gui
Data = "MAIL FROM: <" + nguoigui + ">";
sw.WriteLine(Data);
sw.Flush();
//Doc thong bao tu Server gui ve va xu ly neu can thiet
Console.WriteLine(sr.ReadLine());
//Gui dia chi nguyoi gui
Data = "RCPT TO: <" + nguoinhan + ">";
sw.WriteLine(Data);
sw.Flush();
//Doc thong bao tu Server gui ve va xu ly neu can thiet
Console.WriteLine(sr.ReadLine());
//Bat dau gui noi dung buc thu
Data = "Data";
sw.WriteLine(Data);
sw.Flush();
//Doc thong bao tu Server gui ve va xu ly neu can thiet
Console.WriteLine(sr.ReadLine());
//Gui noi dung buc thu
Data = "SUBJECT:" + tieude + "rn" + body + "rn" + "." + "rn";
sw.WriteLine(Data);
sw.Flush();
//Doc thong bao tu Server gui ve va xu ly neu can thiet
Console.WriteLine(sr.ReadLine());
//Ngat ket noi
Data = "QUIT";
sw.WriteLine(Data);
sw.Flush();
//Doc thong bao tu Server gui ve va xu ly neu can thiet
Console.WriteLine(sr.ReadLine());
sr.Close();
sw.Close();
client.Close();
Console.ReadLine();
}
}
65
Vi t chương trình l y thư ñơn gi n theo giao th c POP3
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;
66
}
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"))
67
txtFrom.Text = s.Substring(5, s.Length - 5);
if (s.ToUpper().StartsWith("TO"))
txtTo.Text = s.Substring(3, s.Length - 3);
if (s.ToUpper().StartsWith("SUBJECT"))
txtSubject.Text = s.Substring(8, s.Length - 8);
}
//Lay phan body
textBox4.Clear();
//MessageBox.Show("Lay body");
while (!sr.EndOfStream) {
s = sr.ReadLine().Trim();
if (s.Equals(".")) break;
textBox4.Text += s + "rn";
}
//MessageBox.Show("Het noi dung buc thu");
}
}
}
3.3. Giao th c HTTP
3.3.1. Cơ b n v giao th c HTTP
HTTP (Hypertext Transfer Protocol) giao th c truy n siêu văn b n. HTTP là
giao th c t ng ng d ng cho Web. Nó ho t ñ ng theo mô hình client/server.
- Client: browser yêu c u, nh n, hi n th các ñ i tư ng Web.
- Server: Web server g i các ñ i tư ng
Hai phiên b n c a giao th c HTTP hi n ñư c ph bi n là HTTP1.0 ñư c ñ c t
trong RFC 1945 và HTTP1.1 ñư c ñ c t trong RFC 2068.
HTTP là giao th c “không tr ng thái” server không lưu l i các yêu c u c a client.
HTTP s d ng giao th c TCP c a t ng giao v n. Các bư c ti n hành t khi client k t
n i t i server sau ñó g i và nh n k t qu t server g i v như sau:
68
+ client kh i t o k t n i TCP (t o socket) v i server, qua c ng 80
+ server ch p nh n k t n i TCP t client
+ Các thông ñi p HTTP (thông ñi p t ng ng d ng) ñư c trao ñ i gi a browser
(HTTP client) và Web server (HTTP server)
+ ðóng k t n i TCP.
Chúng ta xem m t ví d v quá trình trao ñ i gi a browser và Web server như sau:
Có hai ki u thông ñi p HTTP là yêu c u (Request) và tr l i (Response). Các
thông ñi p ñư c ñ nh d ng ki u mã ASCII.
ð nh d ng thông ñi p yêu c u HTTP
5. HTTP client nh n thông ñi p
tr l i bao g m t p html,
hi n th html.Phân tích t p
html file, tìm 10 jpeg ñ i
tý ng ñý c tham chi u
6. Các bư c t 1 ñ n 5 ñư c l p
l i cho t ng ñ i tư ng trong
10 ñ i tư ng jpeg
4. HTTP server ñóng k t n i TCP.
time
User nh p URL
www.someSchool.edu/someDepartment/home.index
1a. HTTP client kh i t o k t n i
TCP t i HTTP server (ti n
trình)t i ñ a ch
www.someSchool.edu. C ng
m c ñ nh là 80.
2. HTTP client g i thông ñi p yêu
c u HTTP (bao g m URL)
vào trong TCP connection
socket
1b. HTTP server ñi ch
www.someSchool.edu ñ i
k t n i TCP c ng 80, ch p
nh n k t n i, thông báo l i
cho client.
3. HTTP server nh n thông ñi p yêu
c u,l y các ñ i tý ng ñý c yêu c u
g i vào trong thông ñi p tr l i,
(someDepartment/home.index) g i
thông ñi p vào socket
(bao g m text,
tham chi u t i 10
nh d ng jpeg)
69
ð nh d ng thông ñi p tr l i HTTP
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òng tr ng thái
(mã tr ng thái)
Nh ng dòng header
d li u,e.g.,
t p html ñý c
yêu c u
GET /somedir/page.html HTTP/1.0
User-agent: Mozilla/4.0
Accept: text/html, image/gif,image/jpeg
Accept-language:fr
(CR,LF)
Nh ng dòng header
CR,LF,kí hi u k t
thúc thông ñi p
Dòng yêu c u
(l nh GET, POST,
HEAD)
70
Quá trình trao ñ i gi a Browser và Web Server có th ñư c minh h a như hình sau:
Mã tr ng thái trong thông ñi p HTTP Response: ðư c ghi dòng ñ u tiên trong thông
ñi p response t server v client.
M t s mã thư ng g p:
200 OK
Yêu c u thành công,các ñ i tư ng ñư c yêu c u ph n sau thông ñi p.
301 Moved Permanently
ð i tư ng ñư c yêu c u ñã ñư c chuy n và ñ a ch m i c a ñ i tư ng ñư c ñ t
trong trư ng Location:
400 Bad Request
Server không hi u ñư c thông ñi p yêu c u
404 Not Found
Tài li u ñư c yêu c u không có trong server
505 HTTP Version Not Supported
Server không h tr version c a giao th c HTTP.
- ð ki m tra các l nh c a HTTP bên phía Client chúng ta có th th c hi n như sau:
+ Telnet t i Web server
71
+ L nh GET trong thông ñi p HTTP
+ Xem thông ñi p response ñư c g i v t Server
- Gõ các l nh khác ñ ki m tra.
3.3.2. Cài ñ t HTTP Client/Server
a. Chương trình HTTP Client
using System;
using System.IO;
using System.Net.Sockets;
using System.Windows.Forms;
namespace HttpView {
public partial class MainForm : Form
{
[STAThread]
public static void Main(string[] args){
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
public MainForm(){
//
// The InitializeComponent() call is required for Windows Forms designer
support.
//
InitializeComponent();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
// G i yêu c u và nh n v ph n h i t web server
void BtGoClick(object sender, EventArgs e){
//Thêm ti n t http:// n u không có
if (txtAddress.Text.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
== false)
txtAddress.Text = "http://" + txtAddress.Text;
TcpClient client = new TcpClient();
try{
client.Connect(GetHost(txtAddress.Text), GetPort(txtAddress.Text));
}
catch{
T o k t n i TCP c ng 80
(c ng m c ñ nh cho HTTP server)
at www.eurecom.fr.
telnet www.eurecom.fr 80
GET /~ross/index.html HTTP/1.0 G i thông ñi p yêu c u l y t p
Index.html trong thư m c ~ross
v client
72
rtfBody.Text = "Không th k t n i ñ n server";
return;
}
StreamWriter OutStream = new StreamWriter(client.GetStream());
StreamReader InpStream = new StreamReader(client.GetStream());
// G i ñi yêu c u b ng phương th c GET
OutStream.WriteLine("GET " + txtAddress.Text + " HTTP/1.0");
OutStream.WriteLine("Content-Type:text/html");
OutStream.WriteLine("Content-Language:en");
OutStream.WriteLine();
OutStream.Flush();
//L y ph n Header
rtfHeader.Text = "";
string s;
while (null != (s = InpStream.ReadLine())){
if (s.Equals("")) break;
rtfHeader.Text += s;
}
//L y ph n Body
rtfBody.Text = "";
int c;
while (true){
c = InpStream.Read();
if (c == -1) break;
rtfBody.Text += (char)c;
}
client.Close();
}
// Khi gõ Enter thì g i ñi yêu c u
void TxtAddressKeyPress(object sender, KeyPressEventArgs e){
if ((int)e.KeyChar == 13)
btGo.PerformClick();
}
// L y v tên máy trong URL
internal string GetHost(string url){
url = url.ToLower();
Uri tmp = new Uri(url);
return tmp.Host;
}
// L y v s hi u c ng trong URL
internal int GetPort(string url){
Uri tmp = new Uri(url);
return tmp.Port;
}
}
}
b. Chương trình HTTP Server
using System;
using System.IO;
73
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ý yêu c u c a m i máy khách
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 ph n header c a gói d li u g i t máy khách
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("---------------------------------------");
}
//Ph n h i yêu c u cho máy khách
private void sendResponse(TcpClient client) {
StreamWriter response = new StreamWriter(client.GetStream());
response.Write(_mainPage);
response.Flush();
}
//M i ph n h i v trình duy t
private const String _mainPage =
"HTTP/1.0 200 OKn" +