TÀI LIỆU BỒI DƯỠNG HỌC SINH GIỎI LÝ LUẬN VĂN HỌC NĂM HỌC 2023-2024 - MÔN NGỮ ...
Lap trinhmangvoic sharp
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
1
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
2
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
Application Presentation
(Upper Layer) Session
Transport Layer
Network Layer Data Lower Layer
Data Link
Physical
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
3
4. Application ti p gi a ngư i s d ng và các
chương trình ng d ng
- L p trình bày: cách th c chu n ASSCII
hoá d li u và trình bày s li u
Presentation EBCDIC
- Có ch c năng ñ c bi t là mã hoá
JPEC
d li u ngư i s dung
- L p phiên: thi t l p, duy trì và NFS, SQL
hu b m t phiên làm vi c
Session
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
4
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
5
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
6
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
0 1 2 3 4 8 16 24
Class A 0 Netid Hostid
Class B 1 0 Netid Hostid
Class C 1 1 0 Netid Hostid
Class D 1 1 1 0 Multicast address
Class E 1 1 1 1 0 Reverved for future use
7
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
8
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 uk tn 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
9
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
10
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
11
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 tn im 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];
12
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);
13
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;
14
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);
}
15
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;
16
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;
17
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;
18
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();
19
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
20
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 T o m t TcpClient và g n cho nó m t EndPoint c c b .
(IPEndPoint)
(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
T o m t ñ i tư ng TcpClient và k t n i ñ n m t máy có
(RemoteHost: String,
ñ a ch và s hi u c ng ñư c truy n vào.. RemoteHost có
Int32)
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 K t n i ñ n m t máy TCP khác có Tên và
(RemoteHost, s hi u c ng.
Port)
21
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.
22
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: T o m t TcpListener và l ng nghe t i c ng ch ñ nh.
Int32)
TcpListener T o m t TcpListener v i giá tr Endpoint truy n vào.
(IPEndPoint)
TcpListener T o m t TcpListener và l ng nghe các k t n i ñ n t i
(IPAddress, Int32)
ñ 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) {
23
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
24
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;
25
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
26
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
27
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.
Requests Started By… Description of Request Requests Ended BY…
BeginAccept() To accept an incoming EndAccept()
connection
BeginConnect() To connect to a remote EndConnect()
host
BeginReceive() To retrieve data from a EndReceive()
socket
BeginReceiveFrom() To retrieve data from a EndReceiveFrom()
specific remote host
BeginSend() To send data from a EndSend()
socket
BeginSendTo() To send data to a EndSendTo()
specific remote host
- ð 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()
28
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()
29
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:
30
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;
31
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)
{
32
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);
33
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;
34
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():
35
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);
36
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;
37
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);
38
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
39
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 Mô t
Name
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 Mô t
Name
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.
40
41. Public Property Mô t
Name
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) {
41
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:
42
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;
43
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);
44
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
{
46
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();
47
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();
}
48
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
49
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()
50
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();
}
}
51
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();
}
}
52
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,
53
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
55
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();
56
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
57
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);
58