CHNG 1: CC KIN THC C BN V MNG MY TNH.......................................3
1.1. M hnh tham kho 7 tng OSI........................................................................................3 1.2. H giao thc TCP/IP........................................................................................................5 1.3. So snh gia hai giao thc TCP v UDP.........................................................................6 1.4. Cng giao thc.................................................................................................................7 1.5. a ch IP, cc a ch IP dnh ring................................................................................7 1.6. a ch tn min: loi A, loi MX.. .................................................................................8 1.7. Mt s giao thc tng ng dng: HTTP, SMTP, POP3, FTP... ...................................8 CHNG 2: LP TRNH MNG TRONG .NET FRAMEWORK ........................................9 2.1. Socket hng kt ni (TCP Socket) ................................................................................9 2.1.1. Gii thiu v NameSpace System.Net v System.Net.Sockets ..............................10 2.1.2. Vit chng trnh cho pha my ch.......................................................................11 2.1.3. Vit chng trnh cho pha my khch...................................................................13 2.1.4. S dng cc lung nhp xut vi Socket................................................................14 2.2. Socket khng hng kt ni (UDP Socket)...................................................................17 2.2.1. Vit chng trnh cho pha my ch.......................................................................17 2.2.2. Vit chng trnh cho pha my khch...................................................................18 2.2.3. S dng lp System.IO.MemoryStream to vng m nhp xut.....................20 2.3. S dng cc lp h tr c xy dng t lp Soket .....................................................20 2.3.1. Lp TCPClient........................................................................................................21 2.3.2. Lp TCPListener ....................................................................................................22 2.3.3. Lp UDPClient .......................................................................................................24 2.4. Socket khng ng b....................................................................................................26 2.4.1. M hnh x l s kin ca windows.......................................................................26 2.4.2. S dng Socket khng ng b ..............................................................................27 2.4.3. V d v Socket khng ng b..............................................................................28 2.4.4. S dng cc phng thc Non-blocking ................................................................35 2.5. S dng Thread trong cc ng dng mng....................................................................39 2.5.1. S dng Thread trong chng trnh .Net ................................................................40 2.5.2. S dng Thread trong cc chng trnh Server ......................................................41 2.5.3. S dng Thread gi/nhn d liu.......................................................................41 2.5.4. S dng ThreadPool trong cc chng trnh .Net ..................................................43 2.5.5. S dng ThreadPool trong cc chng trnh Server...............................................47 2.6. K thut IP Multicasting................................................................................................48 2.6.1. Broadcasting l g?..................................................................................................48 2.6.2. S dng Broadcasting gi d liu n nhiu my trong mng cc b ..............48 2.6.3. Multicasting l g? ..................................................................................................49 2.6.4. Socket Multicasting trong .Net ...............................................................................50 2.7 Bi tp p dng ...............................................................................................................53 CHNG 3: XY DNG NG DNG MNG...................................................................55 3.1. Giao thc ICMP.............................................................................................................55 3.1.1. S dng Raw Socket ...............................................................................................55 3.1.2. S dng giao thc ICMP v Raw Socket xy dng chng trnh Ping.............57 3.1.3. S dng giao thc ICMP v Raw Socket xy dng chng trnh TraceRoute .58 3.2. Giao thc SMTP, POP3.................................................................................................60 3.2.1. C bn v h thng Mail v giao thc SMTP, POP3 .............................................60 3.2.2. Ci t SMTP, POP3 Client/Server ........................................................................60 3.3. Giao thc HTTP.............................................................................................................67 3.3.1. C bn v giao thc HTTP .....................................................................................67 3.3.2. Ci t HTTP Client/Server....................................................................................68 3.4. Giao thc FTP................................................................................................................74 3.4.1. C bn v giao thc FTP ........................................................................................74 3.4.2. Ci t FTP Client/Server.......................................................................................84 2 3.5. DNS (Domain Name Server) .........................................................................................88 3.5.1. Vn phn gii tn min ......................................................................................88 3.5.2. Trin khai DNS MX (Mail Exchange) ...................................................................89 3.6 Tho lun v cc ng dng khc thng gp .................................................................93 3.7 Bi tp p dng ...............................................................................................................93 CHNG 4: XY DNG NG DNG NHIU LP ..........................................................94 4.1. M hnh 2 lp (two tier), 3 lp (three tier) v n lp. .....................................................94 4.2. Remoting........................................................................................................................98 4.2.1. Gii thiu v Remoting.........................................................................................102 4.2.2. Khai bo, ci t v ng k giao din t xa........................................................102 4.2.3. Triu gi phng thc t xa .................................................................................107 4.3. Web Serive...................................................................................................................107 4.3.1. Gii thiu v Web Serives ....................................................................................107 4.3.2. Giao thc SOAP ...................................................................................................109 4.3.3. Xy dng Web Services........................................................................................112 4.3.4. Triu gi Web Services t ng dng .NET, Java v cc ngn ng khc .............114 4.4 Tho lun v cc ng dng phn tn ............................................................................116 4.5. Bi tp p dng ............................................................................................................116 3 CHNG 1: CC KIN THC C BN V MNG MY TNH 1.1. M hnh tham kho 7 tng OSI M hnh kt ni h thng m c T chc quc t v tiu chun ho ISO (International Organizaiton for Standardization) a ra nhm cung cp mt m hnh chun cho cc nh sn xut v cung cp sn phm vin thng p dng theo pht trin cc sn phm vin thng. tng m hnh ho c to ra cn nhm h tr cho vic kt ni gia cc h thng v modun ho cc thnh phn phc v mng vin thng. a. Chc nng ca m hnh OSI: - Cung cp kin thc v hot ng ca kt ni lin mng - a ra trnh t cng vic thit lp v thc hin mt giao thc cho kt ni cc thit b trn mng. M hnh OSI cn c mt s thun li sau : - Chia nh cc hot ng phc tp ca mng thnh cc phn cng vic n gin. - Cho php cc nh thit k c kh nng pht trin trn tng modun chc nng. - Cung cp cc kh nng nh ngha cc chun giao tip c tnh tng thch cao plug and play v tch hp nhiu nh cung cp sn phm. b. Cu trc m hnh OSI: M hnh OSI gm 7 lp (level), mi lp thc hin cc chc nng ring cho hot ng kt ni mng. Hnh 1-1 M t by lp OSI. 4 lp u nh ngha cch thc cho u cui thit lp kt ni vi nhau trao i d liu. 3 lp trn dng pht trin cc ng dng u cui kt ni vi nhau v ngi dng. Aplication Presentation
Application (Upper Layer) Session Transport Layer Network Layer Data Link Physical
Data Lower Layer Cc lp trn 3 lp trn cng ca m hnh OSI thng c gi l cc lp ng dng (Application layers) hay cn gi l cc lp cao. Cc lp ny thng lin quan ti giao tip vi ngi dng, nh dng ca d liu v phng thc truy nhp cc ng dng . Hnh 1-2 M t cc lp trn v cung cp thng tin vi cc chc nng ca n qua v d: - Lp ng dng: chc nng giao Telnet, HTTP 4 Application
tip gia ngi s dng v cc chng trnh ng dng
Presentation - Lp trnh by: cch thc chun ho d liu v trnh by s liu - C chc nng c bit l m ho d liu ngi s dung ASSCII EBCDIC JPEC
Session - Lp phin: thit lp, duy tr v hu b mt phin lm vic NFS, SQL Transport Layer Network Layer Data Link Physical - Application layer : y l lp cao nht trong m hnh. N l ni m ngi s dng hoc kt ni cc chng trnh ng dng vi cc th tc cho php truy nhp vo mng. - Presentation layer : Lp presentation cung cp cc m v chc nng chuyn i m c cung cp bi lp ng dng. Cc chc nng m bo rng d liu t lp ng dng trong mt h thng c th c c bi lp ng dng ca mt h thng khc. VD : dng m ho d liu t lp ng dng : nh m ho nh jpeg , gif. M cho php ta c th hin ln trang web . - Session layer : c s dng thit lp, duy tr v kt thc phin lm vic gia cc lp presentation. Vic trao i thng tin lp ny bao gm yu cu dch v v p ng yu cu ca cc ng dng trn thit b khc. Cc lp di. 4 lp di ca m hnh OSI s dng nh ngha lm th no d liu c truyn i trong cc dy ni vt l, cc thit b mng v i n trm u cui cui cng l n cc lp ng dng. Qun sch ny ta ch quan tm n 4 lp cui. V s xem xt tng lp mt cch chi tit giao thip gia cc lp trong m hnh OSI: S dng phng php protocal stack kt ni gia hai thit b trong mng. Protocal stack l mt tp hp cc quy nh dng nh ngha lm th no d liu truyn qua mng. V d vi : TCP/IP mi Layer cho php d liu truyn qua. Cc lp trao i cc thng tin cung cp cuc lin lc gia hai thit b trong mng. Cc lp giao tip vi nhau s dng Protocal Data Unit (PDU). Thng tin iu khin ca PDU c thm 5 vo vi d liu lp trn. V thng tin iu khin ny nm trong trng gi l trng header v trailer. Hnh 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 thc TCP/IP Cc tng ca giao thc TCP/IP so vi cc tng ca m hnh OSI
Application: Xc nhn quyn, nn d liu v cc dch v cho ngi dng Transport: X l d liu gia cc h thng va cung cp vic truy cp mng cho cc ng dng Network: Tm ng cho cc packet 6 Link: Mc OS hoc cc thit b giao tip mng trn mt my tnh Mt s im khc nhau ca TCP/IP v m hnh OSI + Lp ng dng trong TCP/IP x l chc nng ca lp 5,6,7 trong m hnh OSI + Lp transport trong TCP/IP cung cp c ch UDP truyn khng tin cy, transport trong OSI lun m bo truyn tin cy + TCP/IP l mt tp ca cc protocols (mt b giao thc) + TCP/IP xy dng trc OSI Quy trnh ng gi d liu trong m hnh TCP/IP nh sau:
1.3. So snh gia hai giao thc TCP v UDP 7
1.4. Cng giao thc L mt s nm trong khong 1..65535 dng phn bit gia 2 ng dng mng vi nhau gn vi a ch IP v Socket Mt s cng v cc giao thc thng dng: + FTP: 21 + Telnet: 23 + SMTP: 25 + POP3: 110 + HTTP:80 1.5. a ch IP, cc a ch IP dnh ring Reverved for future use 0 1 1 1 1 Class E Multicast address 0 1 1 1 Class D Hostid Netid 0 1 1 Class C Hostid Netid 0 1 Class B Hostid Netid 0 Class A 24 16 8 4 3 2 1 0 Reverved for future use 0 1 1 1 1 Class E Multicast address 0 1 1 1 Class D Hostid Netid 0 1 1 Class C Hostid Netid 0 1 Class B Hostid Netid 0 Class A 24 16 8 4 3 2 1 0
8
1.6. a ch tn min: loi A, loi MX..
1.7. Mt s giao thc tng ng dng: HTTP, SMTP, POP3, FTP... - Chng ta s nghin cu chi tit cc giao thc ny chng 3 9
CHNG 2: LP TRNH MNG TRONG .NET FRAMEWORK 2.1. Socket hng kt ni (TCP Socket) Socket l mt giao din lp trnh ng dng (API) mng Thng qua giao din ny chng ta c th lp trnh iu khin vic truyn thng gia hai my s dng cc giao thc mc thp l TCP, UDP Socket l s tru tng ho mc cao, c th tng tng n nh l thit b truyn thng hai chiu gi nhn d liu gia hai my tnh vi nhau. Cc loi Socket Socket hng kt ni (TCP Socket) Socket khng hng kt ni (UDP Socket) Raw Socket c im ca Socket hng kt ni C 1 ng kt ni o gia 2 tin trnh Mt trong 2 tin trnh phi i tin trnh kia yu cu kt ni. C th s dng lin lc theo m hnh Client/Server Trong m hnh Client/Server th Server lng nghe v chp nhn mt yu cu kt ni Mi thng ip gi u c xc nhn tr v Cc gi tin chuyn i tun t c im ca Socket khng hng kt ni Hai tin trnh lin lc vi nhau khng kt ni trc tip Thng ip gi i phi km theo a ch ca ngi nhn Thng ip c th gi nhiu ln Ngi gi khng chc chn thng ip ti tay ngi nhn Thng ip gi sau c th n ch trc thng ip gi trc . S hiu cng ca Socket 10 c th thc hin cc cuc giao tip, mt trong hai qu trnh phi cng b s hiu cng ca socket m mnh s dng. Mi cng giao tip th hin mt a ch xc nh trong h thng. Khi qu trnh c gn mt s hiu cng, n c th nhn d liu gi n cng ny t cc qu trnh khc. Qu trnh cn li cng yu cu to ra mt socket.
2.1.1. Gii thiu v NameSpace System.Net v System.Net.Sockets Cung cp mt giao din lp trnh n gin cho rt nhiu cc giao thc mng. C rt nhiu lp lp trnh Ta quan tm lp IPAdress, IPEndPoint, DNS, Lp IPAdress Mt s Field cn ch : Any: Cung cp mt a ch IP ch ra rng Server phi lng nghe trn tt c cc Card mng Broadcast: Cung cp mt a ch IP qung b Loopback: Tr v mt a ch IP lp AdressFamily: Tr v h a ch ca IP hin hnh Lp IPAddress Mt s phng thc cn ch : Phng thc khi to IPAddress(Byte[]) IPAddress(Int64) IsLoopback: Cho bit a ch c phi a ch lp khng Parse: Chuyn IP dng xu v IP chun ToString: Tr a ch IP v dng xu TryParse: Kim tra IP dng xu c hp l khng? Lp IPEndPoint Mt s phng thc cn ch : Phng thc khi to IPEndPoint (Int64, Int32) IPEndPoint (IPAddress, Int32) Create: To mt EndPoint t mt a ch Socket ToString : Tr v a ch IP v s hiu cng theo khun dng aCh: Cng, v d: 192.168.1.1:8080 Lp DNS Mt s thnh phn ca lp: HostName: Cho bit tn ca my c phn gii GetHostAddress: Tr v tt c IP ca mt trm GetHostEntry: Gii p tn hoc a ch truyn vo v tr v i tng IPHostEntry 11 GetHostName: Ly v tn ca my tnh cc b NameSpace System.Net.Sockets Mt s lp hay dng: TcpClient, UdpClient, TcpListener, Socket, NetworkStream, to ra Socket Socket(AddressFamily af, SocketType st, ProtocolType pt) SocketType Protocoltype Description Dgram Udp Connectionless communication Stream Tcp 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. Vit chng trnh cho pha my ch Vit chng trnh cho pha my ch To mt Socket Lin kt vi mt IPEndPoint cc b Lng nghe kt ni Chp nhn kt ni Gi nhn d liu theo giao thc thit k 12 ng kt ni sau khi hon thnh v tr li trng thi lng nghe ch kt ni mi Vit chng trnh cho pha my 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(); //Gi nhn d liu theo giao thc thit k . newsock.Close(); Chng trnh 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. Vit chng trnh cho pha my khch Vit chng trnh cho pha my khch Xc nh a ch ca Server To Socket Kt ni n Server Gi nhn d liu theo giao thc thit k ng Socket Vit chng trnh cho pha my khch IPEndPoint ipep = new IPEndPoint(Ipaddress.Parse("192.168.1.6"), 9050); Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); server.Connect(ipep); Chng trnh 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 dng cc lung nhp xut vi Socket T Socket ta c th to ra lung nhp xut vi Socket l s dng lp 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 chng trnh Client/Server s dng NetworkStream gi v nhn d liu Chng trnh Client s dng 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(); } } Chng trnh Server s dng NetworkStream: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; class Program { static void Main(string[] args) { IPEndPoint iep=new IPEndPoint(IPAddress.Parse("127.0.0.1"),2009); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Bind(iep); server.Listen(10); Socket client = server.Accept(); byte[] data; NetworkStream ns = new NetworkStream(client); while (true) { data = new byte[1024]; int rec = ns.Read(data, 0, data.Length); string s = Encoding.ASCII.GetString(data, 0, rec); Console.WriteLine(s); data = new byte[1024]; s = s.ToUpper(); if (s.Equals("QUIT")) break; data = Encoding.ASCII.GetBytes(s); ns.Write(data, 0, data.Length); } 16 client.Close(); server.Close(); } } Trn c s ca NetworkStream ta c th ni thm cc lung nhp xut theo hng k t nh StreamReader, StreamWriter Sau y l mt v d v chng trnh Client/Server s dng lung nhp xut, chng trnh Server chp php Client gi ln yu cu, nu yu cu l GetDate khng phn bit ch hoa ch thng th Server tr v cho Client ngy hin ti, nu yu cu l GetTime khng phan bit hoa thng th Server tr v gi hin ti, nu l Quit th Server ngt kt ni vi Client, khng phi cc trng hp trn th thng bo khng hiu lnh. Chng trnh pha Client: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; class DateTimeClient { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(iep); NetworkStream ns = new NetworkStream(client); StreamReader sr = new StreamReader(ns); StreamWriter sw = new StreamWriter(ns); while (true) { string input = Console.ReadLine(); sw.WriteLine(input); sw.Flush(); if (input.ToUpper().Equals("QUIT")) break; string kq = sr.ReadLine(); Console.WriteLine(kq); } sr.Close(); sw.Close(); ns.Close(); client.Close(); } } Chng trnh pha Server: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; 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 khng hng kt ni (UDP Socket) Chng trnh pha my ch To mt Socket Lin kt vi mt IPEndPoint cc b Gi nhn d liu theo giao thc thit k ng Socket Chng trnh pha my khch Xc nh a ch Server To Socket Gi nhn d liu theo giao thc thit k ng Socket
2.2.1. Vit chng trnh cho pha my 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. Vit chng trnh cho pha my khch using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets;
class Program { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); String s = "Chao server"; byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes(s); client.SendTo(data, iep); EndPoint remote = (EndPoint)iep; 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 dng Socket khng hng kt ni vit chng trnh chat gia 2 my nh sau: (Sau ny chng ta c th s dng lp 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 + "\r\n"; } }
2.2.3. S dng lp System.IO.MemoryStream to vng m nhp xut
2.3. S dng cc lp h tr c xy dng t lp Soket 21 2.3.1. Lp TCPClient Mc ch ca lp UDPClient trn l dng cho lp trnh vi giao thc UDP, vi giao thc ny th hai bn khng cn phi thit lp kt ni trc khi gi do vy mc tin cy khng cao. m bo tin cy trong cc ng dng mng, ngi ta cn dng mt giao thc khc, gi l giao thc c kt ni : TCP (Transport Control Protocol). Trn Internet ch yu l dng loi giao thc ny, v d nh Telnet, HTTP, SMTP, POP3 lp trnh theo giao thc TCP, MS.NET cung cp hai lp c tn l TCPClient v TCPListener. - Cc thnh phn ca lp TcpClient + Phng thc khi to: Constructor Method Name Description TcpClient () To mt i tng TcpClient. Cha t thng s g. TcpClient (IPEndPoint) To mt TcpClient v gn cho n mt EndPoint cc b. (Gn a ch my cc b v s hiu cng s dng trao i thng tin v sau) TcpClient (RemoteHost: String, Int32) To mt i tng TcpClient v kt ni n mt my c a ch v s hiu cng c truyn vo.. RemoteHost c th l a ch IP chun hoc tn my. + Mt s thuc tnh: Name Description
Available Cho bit s byte nhn v t mng v c sn c.
Client Tr v Socket ng vi TCPClient hin hnh.
Connected Trng thi cho bit kt ni c n Server hay cha ? + Mt s phng thc: Name Description
Close Gii phng i tng TcpClient nhng khng ng kt ni.
Connect (RemoteHost, Port) Kt ni n mt my TCP khc c Tn v s hiu cng. 22
GetStream Tr v NetworkStream t gip ta gi hay nhn d liu. (Thng lm tham s khi to StreamReader v StreamWriter) .
Khi gn vo StreamReader v StreamWriter ri th ta c th gi v nhn d liu thng qua cc phng thc Readln, writeline tng ng ca cc lp ny.
Ta s dng lp TcpClient vit li chng trnh 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. Lp TCPListener TCPListerner l mt lp cho php ngi lp trnh c th xy dng cc ng dng Server (V d nh SMTP Server, FTP Server, DNS Server, POP3 Server hay server t nh ngha .). ng dng server khc vi ng dng Client ch n lun lun thc hin lng nghe v chp nhn cc kt ni n t Client. 23 Cc thnh phn ca lp TcpListener: + Phng thc khi to: Constructor method Name Description TcpListener (Port: Int32) To mt TcpListener v lng nghe ti cng ch nh. TcpListener (IPEndPoint) To mt TcpListener vi gi tr Endpoint truyn vo. TcpListener (IPAddress, Int32) To mt TcpListener v lng nghe cc kt ni n ti a ch IP v cng ch nh. + Cc phng thc khc Name Description
AcceptSocket Chp nhn mt yu cu kt ni ang ch.
AcceptTcpClient Chp nhn mt yu cu kt ni ang ch. (ng dng s dng ti lnh ny cho n khi no c mt kt ni n)
Pending Cho bit liu c kt ni no ang ch i khng ? (True = c).
Start Bt u lng nghe cc yu cu kt ni.
Stop Dng vic nghe.
S dng lp TcpListener ta vit li chng trnh 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. Lp UDPClient Giao thc UDP (User Datagram Protocol hay User Define Protocol) l mt giao thc phi kt ni (Connectionless) c ngha l mt bn c th gi d liu cho bn kia m khng cn bit l bn sn sng hay cha ? (Ni cch khc l khng cn thit lp kt ni gia hai bn khi tin hnh trao i thng tin). Giao thc ny khng tin cy bng giao thc TCP nhng tc li nhanh v d ci t. Ngoi ra, vi giao thc UDP ta cn c th gi cc gi tin qung b (Broadcast) cho ng thi nhiu my.
Trong .NET, lp UDPClient (nm trong System.Net.Sockets) ng gi cc chc nng ca giao thc UDP. Constructor methosd Description UdpClient () To mt i tng (th hin) mi ca lp UDPClient. UdpClient (AddressFamily) To mt i tng (th hin) mi ca lp UDPClient. Thuc mt dng a ch (AddressFamily) c ch nh. UdpClient (Int32) To mt UdpClient v gn (bind) mt cng cho n. UdpClient (IPEndPoint) To mt UdpClient v gn (bind) mt IPEndpoint (gn a ch IP v cng) cho n. UdpClient (Int32, AddressFamily) To mt UdpClient v gn s hiu cng, AddressFamily 25 UdpClient (String, Int32) To mt UdpClient v thit lp vi mt trm t xa mc nh. PUBLIC Method
Name Description
BeginReceive Nhn d liu Khng ng b t my xa.
BeginSend Gi khng ng b d liu ti my xa
Close ng kt ni.
Connect Thit lp mt Default remote host.
EndReceive Kt thc nhn d liu khng ng b trn
EndSend Kt thc vic gi d liu khng ng b trn
Receive Nhn d liu (ng b) do my xa gi. (ng b c ngha l cc lnh ngay sau lnh Receive ch c thc thi nu Receive nhn c d liu v . Cn nu n cha nhn c d ch mt cht th n vn c ch (blocking))
Send Gi d liu (ng b) cho my xa. V d s dng UdpClient vit chng trnh Chat gia 2 my: Do chng trnh 2 my l nh nhau ta ch cn vit mt chng trnh copy ra s dng. Hnh nh ca 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 + "\r\n"; txtSend.Clear(); if (txtSend.Text.ToUpper().Equals("QUIT")) this.Dispose(); } private void btConnect_Click(object sender, EventArgs e) { Thread tuyen = new Thread(new ThreadStart(NhanDl)); tuyen.Start(); } private void NhanDl() { UdpClient receiver = new UdpClient(int.Parse(txtLocalPort.Text)); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0); while (true) { byte[] data = new byte[1024]; data = receiver.Receive(ref iep); string s = Encoding.UTF8.GetString(data); if (s.Trim().ToUpper().Equals("QUIT")) break; txtReceive.Text += "Receiver: "+ s + "\r\n"; } } } } 2.4. Socket khng ng b 2.4.1. M hnh x l s kin ca windows 27 M hnh x l s kin ca Windows c th hin qua hnh sau: Nh vy thng qua m hnh ny ta c th y nhim cho mt th tc no thc hin khi s kin sy ra trn cc 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 trn chng ta ngoi s kin Click ca button 1 chng ta thm mt x kin khi button1 c nhn l s kin NhanTiep.
2.4.2. S dng Socket khng ng b lp trnh khng ng b vi Socket chng ta s dng cc phng thc cho vic s dng bt ng b 28 Cc phng thc cho vic lp trnh bt ng b c chia lm 2 li thng bt u bng Begin v End: Phng thc bt u bng Begin, bt u mt chc nng v c ng k vi phng thc AsyncCallback Bt u bng End ch chc nng hon thnh khi AsyncCallback c gi. 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 Request Requests 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 Request Requests Started By
- chp nhn kt ni bt ng b ta s dng phng thc BeginAccept() v EndAccept() nh sau: Phng thc BeginAccept() v EndAccept() IAsyncResult BeginAccept(AsyncCallback callback, object state) Socket EndAccept(IAsyncResult iar); Thng c dng 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 phng thc CallAccept thng c vit nh sau: private static void CallAccept(IAsyncResult iar) { Socket server = (Socket)iar.AsyncState; Socket client = server.EndAccept(iar); . . . } - thit lp kt ni theo cch bt ng b chng ta s dng phng thc BeginConnect() v EndConnect() nh sau: Phng thc 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 phng thc Connected thng c vit 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"); } } - gi d liu bt ng b chng ta lm nh sau: + Phng thc 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 phng thc SendData thng c vit nh sau: private static void SendData(IAsyncResult iar) { Socket server = (Socket)iar.AsyncState; int sent = server.EndSend(iar); } Tng t nh giao thc hng kt ni nu ta s dng gi d liu theo giao thc khng hng kt ni chng ta cng thc hin tng t nh sau: Phng thc 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) - nhn d liu bt ng b ta thc hin nh sau: + Nhn d liu vi giao thc hng kt ni: Phng thc BeginReceive v EndReceive() 30 sock.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(ReceivedData), sock); Vi ReceivedData c nh ngha 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); } + Nhn d liu bt ng b vi giao thc khng hng kt ni. Phng thc 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 khng ng b Sau y chng ta s s dng cc phng thc khng ng b vit chng trnh Client/Server theo Socket bt ng b, mi khi Client gi d liu ln Server, n s in ra v gi tr li cho Client. M hnh ca client/server s dng cc phng thc bt ng b nh sau: 31
Chng trnh pha 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()); } } Chng trnh pha Server: using System; using System.Drawing; using System.Net; using System.Net.Sockets; using System.Text; using System.Windows.Forms; class AsyncTcpSrvr :Form { private TextBox conStatus; private ListBox results; private byte[] data = new byte[1024]; private int size = 1024; private Socket server; public AsyncTcpSrvr() { Text = "Asynchronous TCP Server"; Size = new Size(400, 380); 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 dng cc phng thc Non-blocking lp trnh bt ng b chng ta c th s dng cc phng thc Non bloking nh phng thc Poll() v phng thc Select: + Phng thc Poll() bool Poll(int microseconds, SelectMode mode); SelectRead: Poll() tr v true nu mt trong nhng iu kin sau c tho: Nu phng thc Accept() thnh cng Nu c d liu trn Socket Nu kt ni ng SelectWrite: Poll() tr v true nu tho mt trong nhng iu kin sau: Phng thc Connect() thnh cng Nu c d liu trn Socket gi SelectError: Poll() tr v true nu mt trong nhng iu kin sau c tho: Nu phng thc Connect() tht bi Nu c d liu ngoi bng thng chun gi n nhng thuc tnh OutOfBandInline khng c thit lp l true. + Phng thc 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 dng Server s dng phng thc 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 chng ta s vit mt chng trnh Server s dng phng thc Select() chp nhn 2 kt ni n t client v x l tng kt ni. Chng trnh Select Server: using System; using System.Collections; using System.Net; using System.Net.Sockets; using System.Text; class SelectTcpSrvr { public static void Main() { ArrayList sockList = new ArrayList(2); ArrayList copyList = new ArrayList(2); Socket main = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); byte[] data = new byte[1024]; string stringData; 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 } } } } Chng trnh Client: using System; using System.Collections; using System.Net; using System.Net.Sockets; using System.Text; class SelectTcpClient { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); byte[] data = new byte[1024]; string stringData; int recv; sock.Connect(iep); Console.WriteLine("Connected to server"); recv = sock.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("Received: {0}", stringData); while (true) { stringData = Console.ReadLine(); if (stringData == "exit") break; data = Encoding.ASCII.GetBytes(stringData); sock.Send(data, data.Length, SocketFlags.None); data = new byte[1024]; recv = sock.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("Received: {0}", stringData); } sock.Close(); } } 2.5. S dng Thread trong cc ng dng mng 40 Mt s khi nim - a nhim (Multitasking): L kh nng h iu hnh lm nhiu cng vic ti mt thi im - Tin trnh (Process): Khi chy mt ng dng, h iu hnh s cp pht ring cho ng dng b nh v cc ti nguyn khc. B nh v ti nguyn vt l ring bit ny c gi l mt tin trnh. Cc ti nguyn v b nh ca mt tin trnh th ch tin trnh c php truy cp. - Tuyn (Thread): Trong h thng, mt tin trnh c th c mt hoc nhiu chui thc hin tch bit nhau v c th chy ng thi. Mi chui thc hin ny c gi l mt tuyn (Thread). Trong mt ng dng, Thread khi to u tin gi l Thread s cp hay Thread chnh. 2.5.1. S dng Thread trong chng trnh .Net s dng Thread trong .Net ta s dng NameSpace System.Threading - Mt s phng thc thng dng Public Method Name M t Abort() Kt thc Thread Join() Buc chng trnh phi ch cho thread kt thc (Block) th mi thc hin tip (cc cu lnh ng sau Join). Resume() Tip tc chy thread b tm ngng - suspended. Sleep() Static method : Tm dng thread trong mt khong thi gian. Start() Bt u chy (khi ng) mt thread. Sau khi gi phng thc ny, trng thi ca thread chuyn t trng thi hin hnh sang Running. Suspend() Tm ngng (ngh) thread. (Phng thc ny b loi khi phin bn VS.NET 2005) - Mt s thuc tnh thng dng: Public Property Name M t CurrentThread This static property: Tr v thread hin hnh ang chy. IsAlive Tr v gi tr cho bit trng thi thc thi ca thread hin hnh. IsBackground Sets or gets gi tr cho bit 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 tin (dnh nhiu hay t CPU cho thread). Cao nht l 4, thp nht l 0. 41 Public Property Name M t ThreadState Ly v trng thi ca thread (ang dng, hay ang chy) - To mt tuyn trong C#
Thread newThread=newThread(new ThreadStart(newMethod)); . } void newMethod() { . . . } 2.5.2. S dng Thread trong cc chng trnh Server - a tuyn hay c ng dng trong cc chng trnh Server, cc chng trnh i hi ti mt thi im chp nhn nhiu kt ni n t cc Client. - cc chng trnh Server c th x l nhiu Client ti mt thi im ta c m hnh ng dng a tuyn nh sau:
Sau y chng ta vit li chng trnh DateTimeServer c s dng 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 dng Thread gi/nhn d liu ng dng a tuyn trong vic gi nhn d liu chng ta vit chng trnh Chat theo giao thc TCP nh sau: 43
ng dng m hnh x l s kin ca Windows v a tuyn v Socket khng ng b ta ch cn vit mt chng trnh sau dch ra, ta chy ng dng nhn Listen n s lng nghe trong vai tr Server cn khi ta chy v nhn Connect n s ng vai tr Client v kt ni ti Server.
Vn bn chng trnh 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); 45 IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); newsock.Bind(iep); newsock.Listen(5); newsock.BeginAccept(new AsyncCallback(AcceptConn), newsock); } void ButtonConnectOnClick(object obj, EventArgs ea) { results.Items.Add("Connecting..."); client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); client.BeginConnect(iep, new AsyncCallback(Connected), client); } void ButtonSendOnClick(object obj, EventArgs ea) { byte[] message = Encoding.ASCII.GetBytes(newText.Text); newText.Clear(); client.BeginSend(message, 0, message.Length, 0, new AsyncCallback(SendData), client); } void AcceptConn(IAsyncResult iar) { Socket oldserver = (Socket)iar.AsyncState; client = oldserver.EndAccept(iar); results.Items.Add("Connection from: " + client.RemoteEndPoint.ToString()); Thread receiver = new Thread(new ThreadStart(ReceiveData)); receiver.Start(); } void Connected(IAsyncResult iar) { try { client.EndConnect(iar); results.Items.Add("Connected to: " + client.RemoteEndPoint.ToString()); Thread receiver = new Thread(new ThreadStart(ReceiveData)); receiver.Start(); } catch (SocketException) { results.Items.Add("Error connecting"); } } void SendData(IAsyncResult iar) { Socket remote = (Socket)iar.AsyncState; int sent = remote.EndSend(iar); } void ReceiveData() { int recv; 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 dng ThreadPool trong cc chng trnh .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 dng ThreadPool trong cc chng trnh 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;
2.6. K thut IP Multicasting 2.6.1. Broadcasting l g? Broadcast, ting Vit gi l qung b. Trong h thng mng hu tuyn, qung b l thut ng dng ch vic gi mt gi thng tin n tt cc nt mng trong mng. thc hin hnh thc qung b, a ch n ca gi tin s l a ch qung b. C hai loi l: Local Broadcast v Global Broadcast 2.6.2. S dng Broadcasting gi d liu n nhiu my trong mng cc b Gi gi d liu Broadcast using System; using System.Net; using System.Net.Sockets; using System.Text; class BadBroadcast { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9050); byte[] data = Encoding.ASCII.GetBytes("This is a test message"); sock.SendTo(data, iep); sock.Close(); } 49 }
Chng ta phi thit lp nh sau:
class Broadcst { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050); IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050); string hostname = Dns.GetHostName(); byte[] data = Encoding.ASCII.GetBytes(hostname); sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); sock.SendTo(data, iep1); sock.SendTo(data, iep2); sock.Close(); } }
Nhn gi d liu Broadcast class RecvBroadcst { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); sock.Bind(iep); EndPoint ep = (EndPoint)iep; Console.WriteLine("Ready to receive"); byte[] data = new byte[1024]; int recv = sock.ReceiveFrom(data, ref ep); string stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString()); data = new byte[1024]; recv = sock.ReceiveFrom(data, ref ep); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString()); sock.Close(); } } 2.6.3. Multicasting l g? Mt a ch multicast cho php thit b gi d liu ti mt tp xc nh trc cc host, c bit n nh cc nhm multicast, trong cc mng con khc nhau. Mt s a ch Multicast a ch multicast Chc nng 224.0.0.0 a ch c s 224.0.0.1 Tt c cc h thng trn mng con ny 224.0.0.2 Tt c cc Router trn mng con ny 50 224.0.0.5 Cc DR trong OSPF 224.0.1.9 Nhm a ch RIPv2 224.0.1.24 Nhm a ch WINS server C 2 k thut Multicast c s dng + Peer to Peer
+ Central Server
2.6.4. Socket Multicasting trong .Net S dng phng thc SetSocketOption() 51 Socket option c th c s dng Thm mt Socket vo nhm Multicast Loi mt Socket khi nhm Multicast SetSocketOption(SocketOptionLevel,SocketOptionName, optionValue) SocketOptionName AddMembership DropMembership S dng phng thc SetSocketOption() Socket option c th c s dng optionValue l mt i tng ca lp MulticastOption MulticastOption(IPAddress) MulticastOption(IPAddress,IPAddress) V d thm mt Socket vo nhm Multicast 224.100.0.1 sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.100.0.1")); Gi d liu 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(); } }
Nhn d liu 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 Gi d liu Multicast vi 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 vi lp UdpClient JoinMulticastGroup() DropMulticastGroup() JoinMulticastGroup() l phng thc 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 Bi tp p dng 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, 54 new MulticastOption(IPAddress.Parse("224.100.0.1"))); receiver = new Thread(new ThreadStart(packetReceive)); receiver.IsBackground = true; receiver.Start(); } void ButtonSendOnClick(object obj, EventArgs ea) { byte[] message = Encoding.ASCII.GetBytes(newText.Text); newText.Clear(); sock.SendTo(message, SocketFlags.None, multiep); } void ButtonCloseOnClick(object obj, EventArgs ea) { receiver.Abort(); sock.Close(); Close(); } void packetReceive() { EndPoint ep = (EndPoint)multiep; byte[] data = new byte[1024]; string stringData; int recv; while (true) { recv = sock.ReceiveFrom(data, ref ep); stringData = Encoding.ASCII.GetString(data, 0, recv); results.Items.Add("from " + ep.ToString() + ": " + stringData); } } public static void Main() { Application.Run(new MulticastChat()); } } 55
- Giao thc ICMP hot ng trn layer 2 - Internetwork trong m hnh TCP/IP hoc layer 3 - Network trong m hnh OSI Cho php kim tra v xc nh li ca Layer 3 Internetwork trong m hnh TCP/IP bng cch nh ngha ra cc loi thng ip c th s dng xc nh xem mng hin ti c th truyn c gi tin hay khng. Trong thc t, ICMP cn cc thnh phn ca mi gi tin IP c th hot ng c. Cu trc ca gi tin IP v ICMP
+ Type: c th l mt query hay mt li + Code: Xc nh y l loi query hay thng ip li + Checksum: Kim tra v sa li cho d liu ICMP + Message: Tu thuc vo Type v Code
3.1.1. S dng Raw Socket Gi tin ICMP khng s dng TCP hoc UDP nn chng ta khng th s dng cc lp c h tr nh TcpClient hay UdpClient m phi s dng mt Raw Socket Mun to Raw Socket khi to ra Socket bn s dng SocketType.Raw, giao thc ICMP To 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 Gi gi d liu Raw ICMP l giao thc khng hng kt ni S dng phng thc SendTo() ca lp Socket gi Cng trong giao thc ICMP khng quan trng
IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 0); sock.SendTo(packet, iep); Nhn gi d liu Raw S dng phng thc ReceiveForm ca lp Socket D liu nhn v l mt gi tin IP chng ta phi tch ra ly gi tin ICMP Raw Socket khng t ng nh dng gi tin ICMP cho chng ta. Chng ta phi t lm Data Variable Size Type Type 1 byte Byte Code 1 byte Byte Checksum 2 bytes Unsigned 16-bit integer Message multibyte Byte array nh ngha lp v phng thc khi to mc nh class ICMP { public byte Type; public byte Code; public UInt16 Checksum; public int Messagesize; public byte[] Message = new byte[1024]; public ICMP() { } } To ra gi 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 dng giao thc ICMP v Raw Socket xy dng chng trnh 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);
3.1.3. S dng giao thc ICMP v Raw Socket xy dng chng trnh TraceRoute class TraceRoute { public static void Main(string[] argv) { byte[] data = new byte[1024]; int recv, timestart, timestop; Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); IPHostEntry iphe = Dns.Resolve(argv[0]); IPEndPoint iep = new IPEndPoint(iphe.AddressList[0], 0); EndPoint ep = (EndPoint)iep; ICMP packet = new ICMP(); packet.Type = 0x08; packet.Code = 0x00; packet.Checksum = 0; Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 0, 2); Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 2, 2); data = Encoding.ASCII.GetBytes("test packet"); Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length); packet.MessageSize = data.Length + 4; int packetsize = packet.MessageSize + 4; UInt16 chcksum = packet.getCchecksum(); packet.Checksum = chcksum; host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000); int badcount = 0; for (int i = 1; i < 50; i++) { host.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, i); timestart = Environment.TickCount; host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep); try { data = new byte[1024]; recv = host.ReceiveFrom(data, ref ep); timestop = Environment.TickCount; ICMP response = new ICMP(data, recv); if (response.Type == 11) Console.WriteLine("hop {0}: response from {1}, {2}ms", i, ep.ToString(), timestop - timestart); if (response.Type == 0) { Console.WriteLine("{0} reached in {1} hops, {2}ms.", ep.ToString(), i, timestop - timestart); break; 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 thc SMTP, POP3 3.2.1. C bn v h thng Mail v giao thc SMTP, POP3
61
* Giao thc SMTP Mt s lnh c bn ca giao thc SMTP: Lnh M t HELO Hello. S dng xc nh ngi gi in. Lnh ny ny i km vi tn ca host gi in. Trong ESTMP (extended protocol), th lnh ny s l EHLO. MAIL Khi to mt giao dch gi th. N kt hp "from" xc nh ngi gi th. RCPT Xc nh ngi nhn th. DATA Thng bo bt u ni dung thc s ca bc in (phn thn ca th). D liu c m thnh dng m 128-bit ASCII v n c kt thc vi mt dng n cha du chm (.). RSET Hu b giao dch th VRFY S dng xc thc ngi nhn th. NOOP N l lnh "no operation" xc nh khng thc hin hnh ng g QUIT Thot khi tin trnh kt thc SEND Cho host nhn bit rng th cn phi gi n u cui khc.
Mt s lnh khng yu cu phi c c xc nh bng RFC 821 SOML Send or mail. Bo vi host nhn th rng th phi gi n u cui khc hoc hp th. SAML Send and mail. Ni vi host nhn rng bc in phi gi ti ngi dng u cui v hp th. EXPN S dng m rng cho mt mailing list. HELP Yu cu thng tin gip t u nhn th. TURN Yu cu host nhn gi vai tr l host gi th.
- M trng thi ca SMTP Khi mt MTA gi mt lnh SMTP ti MTA nhn th MTA nhn s tr li vi mt m trng thi cho ngi gi bit ang c vic g xy ra u nhn. V di y l bng m trng thi ca SMTP theo tiu chun RFC 821. Mc ca trng thi c 62 xc nh bi s u tin ca m (5xx l li nng, 4xx l li tm thi, 1xx3xx l hot ng bnh thng). - Mt s m trng thi ca SMTP 211 Tnh trng h thng, hay reply gip h thng 214 Thng ip gip . 220 <domain> dch v sn sng 221 <domain> dch v ng knh giao chuyn 250 Hnh ng mail yu cu OK, hon thnh 251 User khng cc b; s hng n <forward-path> 354 Khi ng vic nhp mail; kt thc vi <CLRF>. <CLRF> 421 <domain> dch v khng s dng c, ng knh giao chuyn 450 Khng ly hnh ng mail yu cu; mailbox khng hiu lc 451 Khng nhn hnh ng c yu cu; lu tr ca h thng khng . 500 Li c php; khng chp nhn lnh 501 Li c php trong tham s hay i s 502 Lnh khng c cung cp 503 Dng lnh sai 504 Tham s ca dng lnh khng c cung cp 550 Khng nhn hnh ng c yu cu ; mailbox khng hiu lc [nh mailbox khng tm thy hay khng truy cp c] 551 User khng cc b; vui lng th <forward-path> 552 B qua hnh ng m mail yu cu, vt qu ch nh lu tr 554 Khng nhn hnh ng c yu cu; tn mailbox khng c chp nhn. [nh sai c php mailbox] giao chuyn sai. - nh dng ca mt bc th thng thng khng c phn nh km nh sau:
* Giao thc POP3 Giao thc dng ly th, POP3 Server lng nghe trn cng 110, m t trong RFC 1939 63 - Mt s lnh ca POP3 USER Xc nh username PASS Xc nh password STAT Yu cu v trng thi ca hp th nh s lng th v ln ca th LIST Hin danh sch ca th RETR Nhn th DELE Xo mt bc th xc nh NOOP Khng lm g c RSET Khi phc li nh th xo (rollback) QUIT Thc hin vic thay i v thot ra
3.2.2. Ci t SMTP, POP3 Client/Server Vit chng trnh gi Mail n gin theo giao thc SMTP using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; class Program { static void Main(string[] args) { string nguoigui, nguoinhan, tieude,body; string diachimaychu; int portmaychu; Console.Write("Nhap di chu SMTP Server:"); diachimaychu = Console.ReadLine(); Console.Write("Nhap cong cua may chu:"); portmaychu = int.Parse(Console.ReadLine()); Console.Write("Nhap dia chi nguoi gui:"); nguoigui = Console.ReadLine(); Console.Write("Nhap dia chi nguoi nhan:"); nguoinhan = Console.ReadLine(); Console.Write("Nhap tieu de buc thu:"); tieude = Console.ReadLine(); Console.Write("Nhap noi dung buc thu:"); body= Console.ReadLine(); //Tao Endpoit cua may chu IPEndPoint iep = new IPEndPoint(IPAddress.Parse(diachimaychu), portmaychu); TcpClient client = new TcpClient(); client.Connect(iep); string Data = "Helo"; StreamReader sr = new StreamReader(client.GetStream()); StreamWriter sw = new StreamWriter(client.GetStream()); sw.WriteLine(Data); sw.Flush(); //Doc thong bao tu Server gui ve va xu ly neu can thiet Console.WriteLine(sr.ReadLine()); 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 + "\r\n" + body + "\r\n" + "." + "\r\n"; 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 Vit chng trnh ly th n gin theo giao thc 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 + "\r\n"; } //MessageBox.Show("Het noi dung buc thu"); } } } 3.3. Giao thc HTTP 3.3.1. C bn v giao thc HTTP HTTP (Hypertext Transfer Protocol) giao thc truyn siu vn bn. HTTP l giao thc tng ng dng cho Web. N hot ng theo m hnh client/server. - Client: browser yu cu, nhn, hin th cc i tng Web. - Server: Web server gi cc i tng Hai phin bn ca giao thc HTTP hin c ph bin l HTTP1.0 c c t trong RFC 1945 v HTTP1.1 c c t trong RFC 2068. HTTP l giao thc khng trng thi server khng lu li cc yu cu ca client. HTTP s dng giao thc TCP ca tng giao vn. Cc bc tin hnh t khi client kt ni ti server sau gi v nhn kt qu t server gi v nh sau: 68 + client khi to kt ni TCP (to socket) vi server, qua cng 80 + server chp nhn kt ni TCP t client + Cc thng ip HTTP (thng ip tng ng dng) c trao i gia browser (HTTP client) v Web server (HTTP server) + ng kt ni TCP. Chng ta xem mt v d v qu trnh trao i gia browser v Web server nh sau:
C hai kiu thng ip HTTP l yu cu (Request) v tr li (Response). Cc thng ip c nh dng kiu m ASCII. nh dng thng ip yu cu HTTP 5. HTTP client nhn thng ip tr li bao gm tp html, hin th html.Phn tch tp html file, tm 10 jpeg i tng c tham chiu 6. Cc bc t 1 n 5 c lp li cho tng i tng trong 10 i tng jpeg 4. HTTP server ng kt ni TCP. time User nhp URL www.someSchool.edu/someDepartment/home.index 1a. HTTP client khi to kt ni TCP ti HTTP server (tin trnh)ti a ch www.someSchool.edu. Cng mc nh l 80. 2. HTTP client gi thng ip yu cu HTTP (bao gm URL) vo trong TCP connection socket 1b. HTTP server i ch www.someSchool.edu i kt ni TCP cng 80, chp nhn kt ni, thng bo li cho client. 3. HTTP server nhn thng ip yu cu,ly cc i tng c yu cu gi vo trong thng ip tr li, (someDepartment/home.index) gi thng ip vo socket (bao gm text, tham chiu ti 10 nh dng jpeg) 69
nh dng thng ip tr li 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 ... Dng trng thi (m trng thi) Nhng dng header d liu,e.g., tp html c yu cu GET /somedir/page.html HTTP/1.0 User-agent: Mozilla/4.0 Accept: text/html, image/gif,image/jpeg Accept-language:fr
(CR,LF) Nhng dng header CR,LF,k hiu kt thc thng ip Dng yu cu (lnh GET, POST, HEAD) 70 Qu trnh trao i gia Browser v Web Server c th c minh ha nh hnh sau:
M trng thi trong thng ip HTTP Response: c ghi dng u tin trong thng ip response t server v client. Mt s m thng gp: 200 OK Yu cu thnh cng,cc i tng c yu cu phn sau thng ip. 301 Moved Permanently i tng c yu cu c chuyn v a ch mi ca i tng c t trong trng Location: 400 Bad Request Server khng hiu c thng ip yu cu 404 Not Found Ti liu c yu cu khng c trong server 505 HTTP Version Not Supported Server khng h tr version ca giao thc HTTP. - kim tra cc lnh ca HTTP bn pha Client chng ta c th thc hin nh sau: + Telnet ti Web server 71 + Lnh GET trong thng ip HTTP + Xem thng ip response c gi v t Server - G cc lnh khc kim tra. 3.3.2. Ci t HTTP Client/Server a. Chng trnh 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. // } // Gi yu cu v nhn v phn hi t web server void BtGoClick(object sender, EventArgs e){ //Thm tin t http:// nu khng 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{ To kt ni TCP cng 80 (cng mc nh cho HTTP server) at www.eurecom.fr. telnet www.eurecom.fr 80 GET /~ross/index.html HTTP/1.0 Gi thng ip yu cu ly tp Index.html trong th mc ~ross v client 72 rtfBody.Text = "Khng th kt ni n server"; return; } StreamWriter OutStream = new StreamWriter(client.GetStream()); StreamReader InpStream = new StreamReader(client.GetStream()); // Gi i yu cu bng phng thc GET OutStream.WriteLine("GET " + txtAddress.Text + " HTTP/1.0"); OutStream.WriteLine("Content-Type:text/html"); OutStream.WriteLine("Content-Language:en"); OutStream.WriteLine(); OutStream.Flush(); //Ly phn Header rtfHeader.Text = ""; string s; while (null != (s = InpStream.ReadLine())){ if (s.Equals("")) break; rtfHeader.Text += s; } //Ly phn Body rtfBody.Text = ""; int c; while (true){ c = InpStream.Read(); if (c == -1) break; rtfBody.Text += (char)c; } client.Close(); } // Khi g Enter th gi i yu cu void TxtAddressKeyPress(object sender, KeyPressEventArgs e){ if ((int)e.KeyChar == 13) btGo.PerformClick(); } // Ly v tn my trong URL internal string GetHost(string url){ url = url.ToLower(); Uri tmp = new Uri(url); return tmp.Host; } // Ly v s hiu cng trong URL internal int GetPort(string url){ Uri tmp = new Uri(url); return tmp.Port; } } } b. Chng trnh 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 yu cu ca mi my khch private void processClientRequest(TcpClient client) { Console.WriteLine("May khach su dung cong: " +
(client.Client.RemoteEndPoint as IPEndPoint).Port + "; Dia chi IP may khach: " +
client.Client.RemoteEndPoint.ToString() + "\n"); Console.WriteLine("Yeu cau: "); readRequest(client); sendResponse(client); client.Close(); } //c phn header ca gi d liu gi t my khch private void readRequest(TcpClient client) { StreamReader request = new StreamReader(client.GetStream()); String nextLine;
while (null != (nextLine = request.ReadLine())) { if (nextLine.Equals("")) { break; } else { Console.WriteLine(nextLine); } } Console.WriteLine("---------------------------------------"); }
//Phn hi yu cu cho my khch private void sendResponse(TcpClient client) { StreamWriter response = new StreamWriter(client.GetStream()); response.Write(_mainPage); response.Flush(); } //Mi phn hi v trnh duyt private const String _mainPage = "HTTP/1.0 200 OK\n" + 74 "Content-type: text/html\n" + "Connection: close\n" + "\n<HTML>\n" + "<HEAD>\n" + "<TITLE>Hello World</TITLE>\n" + "</HEAD>\n" + "<BODY> <a href = \"localhost\"> Hello World </a></BODY>\n" + "</HTML> \n\n"; }
class TestWebServer { public static void Main(String[] args) { SimpleWebServer webServer1 = new SimpleWebServer(); webServer1.StartListening(8080); } } 3.4. Giao thc FTP 3.4.1. C bn v giao thc FTP Giao thc FTP l mt giao thc trao i file kh ph bin Khi nim v hot ng c bn ca FTP: Nhng ngi pht trin giao thc FTP cn phi cn bng nhu cu gia vic pht trin mt b giao thc va c nhiu chc nng v va n gin trong trin khai. Do , FTP khng n gin nh a em trai ca n l giao thc TFTP. Hot ng ca giao thc ny c th chia ra thnh nhiu thnh phn nh, hot ng cng nhau thc hin cc cng vic nh khi to kt ni, truyn thng tin iu khin v truyn lnh.
Ni dung m bi vit ny hng ti l a ti ngi c nhng khi nim quan trng nht ng sau giao thc FTP, cng nh gii thch tng quan v nguyn l hot ng ca n.
1 - M hnh hot ng ca FTP, cc thnh phn trong giao thc, v cc thut ng c bn
Giao thc FTP c m t mt cch n gin thng qua m hnh hot ng ca FTP. M hnh ny ch ra cc nguyn tc m mt thit b phi tun theo khi tham gia vo qu trnh trao i file, cng nh v hai knh thng tin cn phi thit lp gia cc thit b . N cng m t cc thnh phn ca FTP c dng qun l cc knh ny c hai pha truyn v nhn. Do , m hnh ny to cho ta mt khi im l tng xem xt hot ng ca FTP mc khi qut.
Tin trnh Server-FTP v User-FTP 75
FTP l mt giao thc dng client/server truyn thng, tuy nhin thut ng client thng thng c thay th bng thut ng user ngi dng do thc t l ngi s dng mi l i tng trc tip thao tc cc lnh FTP trn my clients. B phn mm FTP c ci t trn mt thit b c gi l mt tin trnh. Phn mm FTP c ci t trn my Server c gi l tin trnh Server-FTP, v phn trn my client c gi l tin trnh User-FTP.
Knh iu khin v knh d liu trong FTP
Mt khi nim ct yu m ta cn phi nm v FTP l: mc d giao thc ny s dng kt ni TCP, nhng n khng ch dng mt knh TCP nh phn ln cc giao thc truyn thng khc. M hnh FTP chia qu trnh truyn thng gia b phn Server vi b phn client ra lm hai knh logic: - Knh iu khin: y l knh logic TCP c dng khi to mt phin kt ni FTP. N c duy tr xuyn sut phin kt ni FTP v c s dng ch truyn cc thng tin iu khin, nh cc lnh v cc hi p trong FTP. N khng c dng truyn file - Knh d liu: Mi khi d liu c truyn t server ti client, mt knh kt ni TCP nht nh li c khi to gia chng. D liu c truyn i qua knh kt ni ny do n c gi l knh d liu. Khi file c truyn xong, knh ny c ngt. Vic s dng cc knh ring l nh vy to ra s linh hot trong vic truyn truyn d liu m ta s thy trong cc phn tip theo. Tuy nhin, n cng to cho FTP phc tp nht nh.
Cc tin trnh v thut ng trong FTP
Do cc chc nng iu khin v d liu s dng cc knh khc nhau, nn m hnh hot ng ca FTP cng chia phn mm trn mi thit b ra lm hai thnh phn logic tng ng vi mi knh. Thnh phn Protocol Interpreter (PI) l thnh phn qun l knh iu khin, vi chc nng pht v nhn lnh. Thnh phn Data Transfer Process (DTP) c chc nng gi v nhn d liu gia pha client vi server. Ngoi ra, cung cp cho tin trnh bn pha ngi dng cn c thm thnh phn th ba l giao din ngi dng FTP - thnh phn ny khng c pha server.
Do , c hai tin trnh xy ra pha server, v ba tin trnh pha client. Cc tin trnh ny c gn vi m hnh FTP m t chi tit hot ng ca giao thc FTP. Di y l hnh i chiu cc tin trnh vo trong m hnh FTP: 76
Cc tin trnh pha server:
Cc tin trnh pha server bao gm hai giao thc: - Server Protocol Interpreter (Server-PI): chu trch nhim qun l knh iu khin trn server. N lng nghe yu cu kt ni hng ti t users trn cng dnh ring. Khi kt ni c thit lp, n s nhn lnh t pha User-PI, tr li li, v qun l tin trnh truyn d liu trn server. - Server DataTransfer Process (Server-DTP): lm nhim v gi hoc nhn file t b phn User-DTP. Server-DTP va lm nhim thit lp kt ni knh d liu v lng nghe mt kt ni knh d liu t user. N tng tc vi server file trn h thng cc b c v chp file.
Cc tin trnh pha client:
- User Protocol Interpreter (User-PI): chu trch nhim qun l knh iu khin pha client. N khi to phin kt ni FTP bng vic pht ra yu cu ti pha Server-PI. Khi kt ni c thit lp, n x l cc lnh nhn c trn giao din ngi dng, gi chng ti Server-PI, v nhn phn hi tr li. N cng qun l tin trnh User-DTP. - User Data Transfer Process (User-DTP): l b phn DTP nm pha ngi dng, lm nhim v gi hoc nhn d liu t Server-DTP. User-DTP c th thit lp hoc 77 lng nghe yu cu kt ni knh d liu trn server. N tng tc vi thit b lu tr file pha client. - User Interface: cung cp giao din x l cho ngi dng. N cho php s dng cc lnh n gin hng ngi dng, v cho php ngi iu khin phin FTP theo di c cc thng tin v kt qu xy ra trong tin trnh.
2 - Thit lp knh iu khin v chng thc ngi dng trong FTP:
M hnh hot ng ca FTP m t r cc knh d liu v iu khin c thit lp gia FTP client v FTP server. Trc khi kt ni c s dng thc s truyn file, knh iu khin cn phi c thit lp. Mt tin trnh ch nh sau c dng to kt ni v to ra phin FTP lu bn gia cc thit b truyn files.
Nh trong cc giao thc client/server khc, FTP server tun theo mt lut passive trong knh iu khin. B phn Server Protocol Interpreter (Server-PI) s lng nghe cng TCP dnh ring cho kt ni FTP l cng 21. Pha User-PI s to kt ni bng vic m mt kt ni TCP t thit b ngi dng ti server trn cng . N s dng mt cng bt k lm cng ngun trong phin kt ni TCP.
Khi TCP c ci t xong, knh iu khin gia cc thit b s c thit lp, cho php cc lnh c truyn t User-PI ti Server-PI, v Server-PI s p tr kt qu l cc m thng bo. Bc u tin sau khi knh i vo hot ng l bc ng nhp ca ngi dng (login sequence). Bc ny c hai mc ch: - Access Control - iu khin truy cp: qu trnh chng thc cho php hn ch truy cp ti server vi nhng ngi dng nht nh. N cng cho php server iu khin loi truy cp nh th no i vi tng ngi dng. - Resource Selection - Chn ngun cung cp: Bng vic nhn dng ngi dng to kt ni, FTP server c th a ra quyt nh s cung cp nhng ngun no cho ngi dng c nhn dng .
Trnh t truy cp v chng thc FTP
Quy lut chng thc trong FTP kh n gin, ch l cung cp username/password. Trnh t ca vic chng thc nh sau: 1 - ngi dng gi mt username t User-PI ti Server-PI bng lnh USER. Sau password ca ngi dng c gi i bng lnh PASS. 2 - Server kim tra tn ngi dng v password trong database ngi dng ca n. Nu ngi dng hp l, server s gi tr mt thng bo ti ngi dng rng phin kt 78 ni .c m. Nu ngi dng khng hp l, server yu cu ngi dng thc hin li vic chng thc. Sau mt s ln chng thc sai nht nh, server s ngt kt ni.
Gi s qu trnh chng thc thnh cng, server sau s thit lp kt ni cho php tng loi truy cp i vi ngi dng c cp quyn. Mt s ngi dng ch c th truy cp vo mt s file nht nh, hoc vo mt s loi file nht nh. Mt s server c th cp quyn cho mt s ngi dng c v vit ln server, trong khi ch cho php c i vi nhng ngi dng khc. Ngi qun tr mng c th nh m p ng ng cc nhu cu truy cp FTP.
Mt khi kt ni c thit lp, server c th thc hin cc la chn ti nguyn da vo nhn din ngi dng. V d: trn mt h thng nhiu ngi dng, ngi qun tr c th thit lp FTP khi c bt c ngi dng no kt ni ti, anh ta s t ng c a ti "home directory" ca chnh anh ta. Lnh ty chn ACCT (account) cng cho php ngi dng chn mt ti khon c nhn no nu nh anh ta c nhiu hn mt ti khon.
M rng v bo mt FTP
Ging nh phn ln cc giao thc c, phng php ng nhp n gin ca FTP l mt s k tha t nhng giao thc thi k u ca Internet. Ngy nay, n khng cn bo m tnh an ton cn thit trn mi trng Internet ton cu v username v password c gi qua knh kt ni iu khin di dng clear text. iu ny lm cho cc thng tin ng nhp c th b nghe ln. Chun RFC 2228 v cc phn m rng cho bo mt FTP nh ra thm nhiu ty chn chng thc v m ha phc tp cho nhng ai mun tng thm mc an ton vo trong phn mm FTP ca h.
3 - Qun l knh d liu FTP, kt ni knh d liu dng ch ng (mc nh) v b ng cng vi vic s dng cng
Knh iu khin c to ra gia Server-PI v User-PI s dng qu trnh thit lp kt ni v chng thc c duy tr trong sut phin kt ni FTP. Cc lnh v cc hi p c trao i gia b phn PI (Protocol Interpreter) qua knh iu khin, nhng d liu th khng.
Mi khi cn phi truyn d liu gia server v client, mt knh d liu cn phi c to ra. Knh d liu kt ni b phn User-DTP vi Server-DTP. Kt ni ny cn thit 79 cho c hot ng chuyn file trc tip (gi hoc nhn mt file) cng nh i vi vic truyn d liu ngm, nh l yu cu mt danh sch file trong th mc no trn server. Chun FTP ch nh hai phng thc khc nhau to ra knh d liu. Khc bit chnh ca hai phng thc l mt thit b: pha client hay pha server l pha a ra yu cu khi to kt ni. iu ny nghe qua c v kh n gin, nhng k thc n li kh quan trng.
Kt ni knh d liu dng ch ng
Phng thc u tin i khi cn c gi l kt ni knh d liu dng thng thng (v n l phng php mc nh) v i khi c gi l kt ni dng ch ng ( i chiu vi dng kt ni b ng m ta s xt phn sau). Trong dng kt ni ny, pha Server-DTP khi to knh d liu bng vic m mt cng TCP cho pha User-DTP. Pha server s dng cng c dnh ring, l cng 20 cho knh d liu. Trn my client, mt gi tr cng c chn theo mc nh chnh l cng c s dng i vi knh iu khin, tuy nhin pha client s lun chn hai cng ring bit cho hai knh ny.
Gi s pha User-PI thit lp mt kt ni iu khin t cng bt k ca n l 1678 ti cng iu khin trn server l cng 21. Khi , to mt knh d liu cho vic truyn d liu, pha Server-PI s bo cho pha Server-DTP khi to mt knh kt ni TCP t cng 20 ti cng 1678 ca pha client. Sau khi pha client chp nhn knh c khi to, d liu s c truyn i.
Thc t, vic s dng cng mt cng cho c knh d liu v knh iu khin khng phi l mt hay, n lm cho hot ng ca FTP tr nn phc tp. Do , pha client nn ch nh s dng mt cng khc bng vic s dng lnh PORT trc khi truyn d liu. V d: gi s pha client ch nh cng 1742 vi lnh PORT. Pha Server-DTP sau s to ra mt kt ni t cng 20 ca n ti cng 1742 pha client thay v cng 1678 nh mc nh. Qu trnh ny c m t trong hnh di y. 80
Thng thng, i vi knh d liu FTP, pha server s khi to vic truyn d liu bng cch m kt ni d liu ti client.
Trong trng hp trn, pha client trc tin s a ra lnh PORT yu cu server s dng cng 1742. Sau , server s m kt ni knh d liu t cng 20 mc nh ca n ti cng 1742 pha client. D liu sau s c truyn gia cc thit b qua cc cng ny.
Kt ni knh d liu dng b ng
Phng php k tip c gi l kt ni d liu dng b ng. Pha client s nhn server l pha b ng, lm nhim v chp nhn mt yu cu kt ni knh d liu c khi to t pha client. Server tr li li pha client vi a ch IP cng nh a ch cng m n s s dng. Pha Server-DTP sau s lng nghe mt kt ni TCP t pha User-DTP trn cng ny.
Mc nh, pha client s dng cng mt cng i vi c hai knh iu khin v d liu nh trong trng hp kt ni ch ng trn. Tuy nhin, y, mt ln na pha client c th chn s dng mt gi tr cng khc cho knh d liu. Ta s xt li v d trn mt ln na, vi cng iu khin pha client l 1678 ti cng 21 pha server. 81 Nhng ln ny truyn d liu theo phng thc kt ni b ng, nh m t trong hnh di y:
Pha client s s dng lnh PASV yu cu server rng n mun dng phng thc iu khin d liu b ng. Pha Server-PI s tr li li pha client vi mt gi tr cng m client s s dng, t cng 2223 trn n. Sau pha Server PI s hng cho pha Server-DTP lng nghe trn cng 2223. Pha User-PI cng s hng cho pha User- DTP to mt phin kt ni t cng 1742 pha client ti cng 2223 pha server. Sau khi Server chp nhn kt ni ny, d liu bt u c truyn i.
Cc vn v tnh hiu qu v tnh bo mt trong vic chn mt phng thc kt ni
Vn pha no l pha khi to kt ni knh d liu a ra mt cu hi: s khc nhau gia hai phng thc l g? iu ny cng ging nh vic hi ai thc hin mt cuc in thoi ni b. Cu tr li l s bo mt. Vic FTP s dng nhiu hn mt kt ni TCP c th gii quyt cc vn v phn mm cng nh v phn cng m ngi dng cn phi c m bo s an ton cho h thng ca h.
Khi xem xt vic g s xy ra trong trng hp knh d liu ch ng nh trong v d pha trn: 82 i vi pha client, c mt knh kt ni iu khin c thit lp t cng 1678 client ti cng 21 server. Nhng knh d liu li c khi to t pha server. Do , client s nhn c mt yu cu kt ni ti cng 1678 (hoc cng no khc). Mt s client s nghi ng v vic nhn c nhng kt ni ti nh vy, v trong tnh hung thng thng, client mi l pha khi to kt ni ch khng phi p tr kt ni. Do cc knh kt ni TCP hng ti c th mang theo nhng mi e da nht nh, mt s client c th s ngn chn cc lung kt ni hng ti bng vic s dng tng la.
Ti sao ngi ta li khng lm cho pha client lun chp nhn kt ni t mt ch s port c dng trong knh iu khin? Vn y l v client thng dng cc cng khc nhau cho mi phin kt ni bng vic s dng cu lnh PORT. V ti sao iu ny li c thc hin? V theo lut TCP: sau khi mt kt ni c ng li , c mt khong thi gian trng trc khi cng c th c s dng li iu ny ngn nga tnh trng cc phin kt ni lin tip b ln vi nhau. iu ny s to ra tr khi gi nhiu file do pha client thng dng cc gi tr cng khc nhau cho mi kt ni. iu ny rt hiu qu nhng cng dn ti vic firewall ca client s hi c chp nhn phin kt ni ti vi nhiu gi tr cng khng n nh hay khng.
Vic dng kt ni kiu knh gin tip s gim thiu vn ny mt cch hiu qu. Phn ln cc tng la c nhiu vn lin quan ti kt ni hng v vi cc gi tr cng bt k, hn l gp vn vi cc kt ni hng i. Ta c th xem chi tit hn v vn ny trong chun RFC 1579. Chun ny khuyn ngh rng pha client nn s dng kt ni kiu b ng lm dng mc nh thay v s dng kiu kt ni dng ch ng cng vi lnh PORT, ngn chn tnh trng block theo cng. Tt nhin, phng thc kt ni kiu b ng khng hon ton gii quyt c vn , chng ch y vn v pha server m thi. Pha server, gi y phi i mt vi vic c nhiu knh kt ni hng v trn hng lot cc cng khc nhau. Tuy nhin vic x l cc vn bo mt trn mt nhm nh server vn d hn nhiu so vi vic phi i mt vi mt lng ln cc vn t nhiu client. FTP server phi c cu hnh chp nhn phng thc truyn b ng t client, do cch thng thng thit lp trn server l thit lp chp nhn mt s cng kt ni hng v trn server trong khi vn kha cc yu cu kt ni hng v trn cc cng khc.
4 - Cc phng thc truyn d liu trong FTP
Khi knh d liu c thit lp xong gia Server-DTP vi User-DTP, d liu s c truyn trc tip t pha client ti pha server, hoc ngc li, da theo cc lnh 83 c s dng. Do thng tin iu khin c gi i trn knh iu khin, nn ton b knh d liu c th c s dng truyn d liu. (Tt nhin, hai knh logic ny c kt hp vi nhau lp di cng vi tt c cc kt ni TCP/UDP khc gia hai thit b, do iu ny khng hn ci thin tc truyn d liu so vi khi truyn trn ch mt knh n ch lm cho hai vic truyn d liu v iu khin tr nn c lp vi nhau m thi) FTP c ba phng thc truyn d liu, nu ln cch m d liu c truyn t mt thit b ti thit b khc trn mt knh d liu c khi to, l: stream mode, block mode, v compressed mode
Stream mode
Trong phng thc ny, d liu c truyn i di dng cc byte khng cu trc lin tip. Thit b gi ch n thun y lung d liu qua kt ni TCP ti pha nhn. Khng c mt trng tiu nht nh c s dng trong phng thc ny lm cho n kh khc so vi nhiu giao thc gi d liu ri rc khc. Phng thc ny ch yu da vo tnh tin cy trong truyn d liu ca TCP. Do n khng c cu trc dng header, nn vic bo hiu kt thc file s n gin c thc hin vic pha thit b gi ngt knh kt ni d liu khi truyn xong. Trong s ba phng thc, stream mode l phng thc c s dng nhiu nht trong trin khai FTP thc t. C mt s l do gii thch iu . Trc ht, n l phng thc mc nh v n gin nht, do vic trin khai n l d dng nht. Th hai, n l phng php ph bin nht, v n x l vi cc file u n thun nh l x l dng byte, m khng ti ni dung ca cc file. Th ba, n l phng thc hiu qu nht v n khng tn mt lng byte overload thng bo header.
Block mode
y l phng thc truyn d liu mang tnh quy chun hn, vi vic d liu c chia thnh nhiu khi nh v c ng gi thnh cc FTP blocks. Mi block ny c mt trng header 3 byte bo hiu di, v cha thng tin v cc khi d liu ang c gi. Mt thut ton c bit c s dng kim tra cc d liu c truyn i v pht hin, khi to li i vi mt phin truyn d liu b ngt.
Compressed mode
y l mt phng thc truyn s dng mt k thut nn kh n gin, l run-length encoding c tc dng pht hin v x l cc on lp trong d liu c truyn i 84 gim chiu di ca ton b thng ip. Thng tin khi c nn, s c x l nh trong block mode, vi trng header. Trong thc t, vic nn d liu thng c s dng nhng ch khc, lm cho phng thc truyn kiu compressed mode tr nn khng cn thit na. V d: nu bn ang truyn i mt file qua internet vi modem tng t, modem ca bn thng thng s thc hin vic nn lp 1; cc file ln trn FTP server cng thng c nn sn vi mt s nh dng nh ZIP, lm cho vic nn tip tc khi truyn d liu tr nn khng cn thit. 3.4.2. Ci t FTP Client/Server Trn c s giao thc FTP chng ta thc hin ci t FTP Client/Server minh ha cho giao thc Chng trnh Simple FTP Server: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; class Program { static void Main(string[] args) { string rootDir = "C:/MyFTP"; IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2121); TcpListener server = new TcpListener(iep); server.Start(); TcpClient client = server.AcceptTcpClient(); StreamReader sr = new StreamReader(client.GetStream()); StreamWriter sw = new StreamWriter(client.GetStream()); sw.WriteLine("220 Chao mung ket noi toi MyFTP"); sw.Flush(); while (true) { string request = sr.ReadLine(); string command=""; if(request.Length!=0) command = request.Substring(0, 4); switch (command.ToUpper().Trim()) { case "USER": { sw.WriteLine("331. Nhap pass vao"); sw.Flush(); //sw.Close(); Console.WriteLine(request); break; } case "PASS": { sw.WriteLine("230. Dang nhap thanh cong"); sw.Flush(); Console.WriteLine(request); break; } 85 case "MKD": { string folderName = request.Substring(4, request.Length - 4); folderName = rootDir + "/" + folderName.Trim(); try { Directory.CreateDirectory(folderName); sw.WriteLine("150 Tao thu muc thanh cong"); sw.Flush(); }catch(IOException){ sw.WriteLine("550 Tao thu muc co loi"); sw.Flush(); } break; } case "RETR": { string fileName = request.Substring(4, request.Length - 4); fileName = rootDir + "/" + fileName.Trim(); try { if (File.Exists(fileName)) { //Gui noi dung file ve cho client xu ly sw.WriteLine("150 Truyen File thanh cong"); sw.Flush(); FileStream fs = new FileStream(fileName, FileMode.Open); long totalLenght = fs.Length; byte[] data = new byte[totalLenght]; fs.Read(data, 0, data.Length); sw.Write(totalLenght); char[] kt = Encoding.ASCII.GetChars(data); sw.Write(kt,0,data.Length); sw.Flush(); fs.Close(); } else { sw.WriteLine("550 File khong ton tai tren server"); sw.Flush(); } } catch (IOException) { sw.WriteLine("550 Khong truyen duoc file"); sw.Flush(); } break; } case "STOR": { string fileName = request.Substring(request.LastIndexOf("/"),request.Length-request.LastIndexOf("/")); fileName = rootDir + "/" + fileName.Trim(); try { FileStream fs = new FileStream(fileName, FileMode.CreateNew); long totalLength=sr.Read(); byte[] data = new byte[totalLength]; char[] kt = Encoding.ASCII.GetChars(data); 86 int sobyte = sr.Read(kt, 0, data.Length); fs.Write(data, 0, sobyte); fs.Close(); sw.WriteLine("150 Up file thanh cong"); sw.Flush(); } catch (IOException) { sw.WriteLine("550 Khong truyen duoc file"); sw.Flush(); } break; } case "QUIT": { client.Close(); break; } default: { sw.WriteLine("Sai lenh"); sw.Flush(); break; } } } } } Chng trnh Simple FTP Client: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Net; using System.Net.Sockets; namespace FtpClient { class Program { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2121); TcpClient client = new TcpClient(); client.Connect(iep); StreamReader sr = new StreamReader(client.GetStream()); StreamWriter sw = new StreamWriter(client.GetStream()); Console.WriteLine(sr.ReadLine()); string input; string command = ""; Console.WriteLine("Dang nhap bang USER Ten user, PASS Ten password"); Console.WriteLine("Tao thu muc bang MKD ten thu muc can tao"); Console.WriteLine("Upload bang cach STOR tenfile"); Console.WriteLine("Download bang cach RETR tenfile"); while (true) { input = Console.ReadLine(); 87 command = input.Substring(0, 4).Trim().ToUpper(); switch (command) { case "STOR": { //Doc file gui cho server sw.WriteLine(input); sw.Flush(); FileInfo fl=null; try { fl = new FileInfo(input.Substring(4, input.Length - 4).Trim()); } catch (IOException) { Console.WriteLine("File khong ton tai"); } long totalLength = fl.Length; FileStream fs = fl.OpenRead(); sw.Write(totalLength); byte[] data = new byte[totalLength]; int bytes = fs.Read(data, 0, data.Length); char[] kt = Encoding.ASCII.GetChars(data); sw.Write(kt, 0, data.Length); sw.Flush(); fs.Close(); Console.WriteLine(sr.ReadLine()); break; } case "RETR": { sw.WriteLine(input); sw.Flush(); string s = sr.ReadLine(); Console.WriteLine(s); if (s.Substring(0, 3).Equals("150")) { Console.Write("Nhap vao noi luu tep:"); string filename = Console.ReadLine(); FileStream fs = new FileStream(filename, FileMode.CreateNew); //Doc tep ve; long totalLength = sr.Read(); byte[] data = new byte[totalLength]; char[] kt= new char[data.Length] ; int sobyte = sr.Read(kt, 0, data.Length); data=Encoding.ASCII.GetBytes(kt); fs.Write(data, 0, data.Length); fs.Close(); } break; } default: { sw.WriteLine(input); sw.Flush(); Console.WriteLine(sr.ReadLine()); break; 88 } } if (input.ToUpper().Equals("QUIT")) break; } sr.Close(); sw.Close(); client.Close(); } } } 3.5. DNS (Domain Name Server) 3.5.1. Vn phn gii tn min Domain Name System: L h c s d liu phn tn hot ng c th bc bi cc name servers L giao thc tng ng dng : host, routers yu cu ti name servers xc nh tn min (nh x a ch <->tn min) Note : l mt chc nng ca Internet, hot ng nh l giao thc tng ng dng Rt phc tp. Q: nh x gia a ch IP v tn? Ti sao khng tp trung s kim sot ca DNS ? im hng duy nht - nu name-server cht th c mng Internet s cht theo. Tn ng truyn. C s d liu tp trung s xa vi a s vng Bo tr phc tp. Phi chia tr ! Khng c server no c th lu ton b c tn min v a ch IP tng ng local name servers: Mi ISP,cng ty c local (default) name server Cu hi truy vn ca host v DNS s c chuyn ti local name server Chc nng ca name server: i vi host: lu a ch IP v tn min tng ng ca host C th tm tn min ng vi a ch IP v ngc li c yu cu bi cc local name server khng th xc nh c tn. root name server: c yu cu nu c authoritative name server khng xc nh. Nhn v x l mapping Tr v mapping cho local name server 89 b USC-ISI Marina del Rey, CA l ICANN Marina del Rey, CA e NASA Mt View, CA f Internet Software C. Palo Alto, CA i NORDUnet Stockholm k RIPE London m WIDE Tokyo a NSI Herndon, VA c PSInet Herndon, VA d U Maryland College Park, MD g DISA Vienna, VA h ARL Aberdeen, MD j NSI (TBD) Herndon, VA b USC-ISI Marina del Rey, CA l ICANN Marina del Rey, CA e NASA Mt View, CA f Internet Software C. Palo Alto, CA i NORDUnet Stockholm k RIPE London m WIDE Tokyo a NSI Herndon, VA c PSInet Herndon, VA d U Maryland College Park, MD g DISA Vienna, VA h ARL Aberdeen, MD j NSI (TBD) Herndon, VA
host surf.eurecom.fr mun bit a ch IP ca gaia.cs.umass.edu 1. Yu cu ti local DNS server, dns.eurecom.fr 2. dns.eurecom.fr yu cu ti root name server nu cn thit 3. root name server yu cu authoritative name server, dns.umass.edu, nu cn thit. requesting host surf.eurecom.fr gaia.cs.umass.edu root name server authorititive name server dns.umass.edu local name server dns.eurecom.fr local name server dns.eurecom.fr 1 2 3 4 5 6
90 Root name server: C th khng bit authoritative name server C th bit name server trung gian ,nh c th yu cu tm authoritative name server requesting host surf.eurecom.fr gaia.cs.umass.edu local name server dns.eurecom.fr local name server dns.eurecom.fr 1 2 3 4 5 6 authoritative name server dns.cs.umass.edu intermediate name server dns.umass.edu intermediate name server dns.umass.edu 7 8
DNS example - Truy vn trong DNS c chia thnh cc loi nh sau: Truy vn quy query: Name server l ni phn gi i a ch/tn.Nu n khng phn gii trong ni b,n s gi yu cu n name server khc. Cng vic ca name server liu c qu nng? Truy vn tng tc: Nu khng phn gii c a ch IP/name,name server s gi tr thng i p rng Ti khng bit,hy th hi anh bn cnh ti l A.A l a ch IP ca name server k tip n. requesting host surf.eurecom.fr gaia.cs.umass.edu local name server dns.eurecom.fr local name server dns.eurecom.fr 1 2 3 4 5 6 authoritative name server dns.cs.umass.edu intermediate name server dns.umass.edu intermediate name server dns.umass.edu 7 8 iterated query
- Cu trc bn ghi DNS nh sau: 91 DNS: c s d liu phn tn lu cc bn ghi ngun (RR) Type=NS name : domain (e.g. foo.com) value : a ch IP authoritative name server cho tn min nh dng ca RR : (name, value, type, ttl) nh dng ca RR : (name, value, type, ttl) Type=A name : hostname value : IP address Type=CNAME name : tn b danh cho mt tn thc no : e.g www.ibm.com l tn b danh ca servereast.backup2.ibm.com value : l tn thc Type=MX value : tn ca mailserver
3.5.2. Trin khai DNS MX (Mail Exchange) Chng ta i vit chng trnh cho php ly v thng tin ca mail server 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; using System.Net; using System.Net.Sockets; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btFind_Click(object sender, EventArgs e) { byte[] DNSQuery; byte[] DNSReply; UdpClient dnsClient = new UdpClient(tbServer.Text, 53); DNSQuery = makeQuery(DateTime.Now.Millisecond * 60, tbDomain.Text); dnsClient.Send(DNSQuery, DNSQuery.GetLength(0)); IPEndPoint endpoint = null; DNSReply = dnsClient.Receive(ref endpoint); this.tbStatus.Text = makeResponse(DNSReply, tbDomain.Text); } public byte[] makeQuery(int id, string name) { byte[] data = new byte[512]; byte[] Query; data[0] = (byte)(id >> 8); data[1] = (byte)(id & 0xFF); data[2] = (byte)1; data[3] = (byte)0; data[4] = (byte)0; data[5] = (byte)1; 92 data[6] = (byte)0; data[7] = (byte)0; data[8] = (byte)0; data[9] = (byte)0; data[10] = (byte)0; data[11] = (byte)0; string[] tokens = name.Split(new char[] { '.' }); string label; int position = 12; for (int j = 0; j < tokens.Length; j++) { label = tokens[j]; data[position++] = (byte)(label.Length & 0xFF); byte[] b = System.Text.Encoding.ASCII.GetBytes(label); for (int k = 0; k < b.Length; k++) { data[position++] = b[k]; } } data[position++] = (byte)0; data[position++] = (byte)0; data[position++] = (byte)15; data[position++] = (byte)0; data[position++] = (byte)1; Query = new byte[position + 1]; for (int i = 0; i <= position; i++) { Query[i] = data[i]; } return Query; } public string makeResponse(byte[] data, string name) { int qCount = ((data[4] & 0xFF) << 8) | (data[5] & 0xFF); int aCount = ((data[6] & 0xFF) << 8) | (data[7] & 0xFF); int position = 12; for (int i = 0; i < qCount; ++i) { name = ""; position = proc(position, data, ref name); position += 4; } string Response = ""; for (int i = 0; i < aCount; ++i) { name = ""; position = proc(position, data, ref name); position += 12; name = ""; position = proc(position, data, ref name); Response += name + "\r\n"; } return Response; } private int proc(int position, byte[] data, ref string name) { int len = (data[position++] & 0xFF); if (len == 0) { return position; } int offset; 93 do { if ((len & 0xC0) == 0xC0) { if (position >= data.GetLength(0)) { return -1; } offset = ((len & 0x3F) << 8) | (data[position++] & 0xFF); proc(offset, data, ref name); return position; } else { if ((position + len) > data.GetLength(0)) { return -1; } name += Encoding.ASCII.GetString(data, position, len); position += len; } if (position > data.GetLength(0)) { return -1; } len = data[position++] & 0xFF; if (len != 0) { name += "."; } } while (len != 0); return position; } } 3.6 Tho lun v cc ng dng khc thng gp 3.7 Bi tp p dng 94 CHNG 4: XY DNG NG DNG NHIU LP
4.1. M hnh 2 lp (two tier), 3 lp (three tier) v n lp. Trc y, i vi cc phn mm c s dng lin quan n d liu, thng khi lm ngi lp trnh thng tch hp vic giao tip vi ngi s dng , x l ri ghi xung d liu trn cng mt form (y l m hnh mt lp). Nhng trong kin trc 3 lp (m hnh 3 lp), phi c vic phn bit rch ri gia cc lp ny. M hnh 3 lp c th c m t nh sau:
- Lp th nht : Lp giao din (giao tip vi ngi s dng) : ch thun x l vic giao tip vi ngi s dng, nhp xut, m khng thc hin vic tnh ton, kim tra, x l, hay cc thao tc lin quan n c s d liu. - Lp th hai : Lp x l : Lp ny chuyn thc hin cc x l , kim tra cc rng buc, cc qui tc ng x ca phn mm , cc chc nng ct yu, Vic thc hin ny c lp vi cch thit k cng nh ci t giao din. Thng tin cho lp ny thc hin cc x l ca mnh c ly t lp giao din. - Lp th ba : Lp d liu : Lp ny chuyn thc hin cc cng vic lin quan n d liu. D liu c th ly t c s d liu (Access, SQL Server ) hoc tp tin (text, binary, XML ). i vi c s d liu, lp ny thc hin kt ni trc tip vi c s d liu v thc hin tt c cc thao tc lin quan n c s d liu m phn mm cn thit. i vi tp tin, lp ny thc hin vic c, ghi tp tin theo yu cu ca phn mm. Vic thc hin ny do lp x l gi. 95 R rng, vi m hnh ny, cc cng vic ca tng lp l c lp vi nhau. Vic thay i mt lp khng lm thay i cc lp cn li, thun tin hn cho qu trnh pht trin v bo tr phn mm. Mt s lu : Phn bit vai tr Business Layer v khi nim x l Mi Layer vn c x l ring, c trng ca Layer i khi vic quyt nh 1 x l nm layer no ch mang tnh cht tng i Chng ta cng cn phn bit khi nim 3 tier v 3 layer: 3 tier l m hnh 3 lp vt l cn 3 layer l m hnh logic.
V d minh ha: Xy dng chng trnh tnh tng 2 phn s theo kin trc 3 lp. Theo d liu ca phn s c c ln t tp tin XML, kt qu sau khi c tnh s c ghi xung tp tin XML. Cch lm thng thng l mi vic u c y vo trong 1 form v x l trc tip trong form . Tuy nhin, khi c s thay i xy ra v giao din, x l, hay d liu th vic chnh sa kh kh khn. Do vy, vic xy dng theo kin trc 3 lp s khc phc nhc im ny. Kin trc ca chng trnh nh sau:
Browser Data tier Business tier Web Local Presentation Data Business logic Data Access Web GUI Application Web P h y s i c a l
v i e w
L o g i c a l
v i e w
96
Xy dng lp th hin phn s (TH_PHANSO) S dng User Control ci t cho TH_PHANSO. Thm User Control vo project bng cch chn Project > Add User Control. t tn User Control . Ta c TH_PHANSO.cs
97 Do th hin t s v th hin mu s u l TextBox do trong lp TH_PHANSO cn thit lp cc properties l tuso v mauso c kiu int. public int tuso{ set{ this.txtTuSo.Text = value.ToString(); } get{ return int.Parse(this.txtTuSo.Text); } } public int mauso { set { this.txtMauSo.Text = value.ToString(); } get { return int.Parse(this.txtMauSo.Text); } }
Lp lu tr phn s (LT_PHANSO) Tp tin XML lu tr c nh dng nh sau: <?xml version ="1.0" encoding = "utf-8"?> <PHANSO> <Tu_so>5</Tu_so> <Mau_so>3</Mau_so> </PHANSO> thc hin vic c v ghi d liu XML ta s dng DOM. Khai bo tuso v mauso thc hin vic lu tr public int tuso; public int mauso; Thc hin ci t hm khi to mc nh vi tham s truyn vo l ng dn file XML public LT_PHANSO(string strFilename) { // // TODO: Add constructor logic here // XmlDocument doc = LT_XML.DocTaiLieu(strFilename); if(doc == null) { tuso = 0; 98 mauso = 0; return; } XmlElement ele = doc.DocumentElement; tuso = int.Parse(ele.SelectSingleNode("Tu_so").InnerText); mauso = int.Parse(ele.SelectSingleNode("Mau_so").InnerText); } Thc hin ci t hm ghi phn s vi tham s truyn vo l ng dn file XML public void GhiPhanSo(string strFilename) { XmlDocument doc = new XmlDocument(); XmlElement root = doc.CreateElement("PHANSO"); doc.AppendChild(root); XmlElement ele_Tuso = root.OwnerDocument.CreateElement("Tu_so"); ele_Tuso.InnerText = this.tuso.ToString(); root.AppendChild(ele_Tuso); XmlElement ele_Mauso = root.OwnerDocument.CreateElement("Mau_so"); ele_Mauso.InnerText = this.mauso.ToString(); root.AppendChild(ele_Mauso); LT_XML.GhiTaiLieu(strFilename,doc); } Lp lu tr XML (LT_XML) Vic load v save XmlDocument c tch ra thnh mt lp ring l lp LT_XML public static XmlDocument DocTaiLieu(string strFilename) { XmlDocument kq = new XmlDocument(); try { kq.Load(strFilename); } catch{ return null; } return kq; } public static void GhiTaiLieu(string strFilename, XmlDocument doc) { try{ doc.Save(strFilename); } catch{ } } Lp x l phn s (XL_PHANSO) 99 Lp ny s thc hin ci t cc hm lin quan n x l v tnh ton trn phn s nh nh ngha php cng 2 phn s, rt gn phn s hay cp nht gi tr t i tng th hin. Khai bo 2 i tng ln lt thuc v lp LT_PHANSO v TH_PHANSO gip to lin kt vi tng x l vi 2 tng cn li l tng d liu v tng giao din. private LT_PHANSO lt_ps = null; private TH_PHANSO th_ps = null; Ci t hm khi to mc nh to lin kt vi i tng th hin v i tng x l public XL_PHANSO(LT_PHANSO lt_ps, TH_PHANSO th_ps) { this.lt_ps = lt_ps; this.th_ps = th_ps; this.th_ps.tuso = this.lt_ps.tuso; this.th_ps.mauso = this.lt_ps.mauso; } Ci t phng thc ghi public void Ghi(string strFilename) { this.lt_ps.tuso = this.th_ps.tuso; this.lt_ps.mauso = this.th_ps.mauso; this.lt_ps.GhiPhanSo(strFilename); } Ci t ton t + public static XL_PHANSO operator +(XL_PHANSO ps1,XL_PHANSO ps2) { XL_PHANSO kq = new XL_PHANSO(new LT_PHANSO(), new TH_PHANSO()); kq.th_ps.tuso = ps1.th_ps.tuso * ps2.th_ps.mauso + ps2.th_ps.tuso * ps1.th_ps.mauso; kq.th_ps.mauso = ps1.th_ps.mauso * ps2.th_ps.mauso; return kq; } Ci t hm cp nht t i tng x l phn s khc public void CapNhat(XL_PHANSO ps) { this.th_ps.tuso = ps.th_ps.tuso; this.th_ps.mauso = ps.th_ps.mauso; } Ci t hm rt gn phn s public void RutGon() { int tuso = this.th_ps.tuso; int mauso = this.th_ps.mauso; int maxUC = TimMaxUocChung(tuso,mauso); tuso = tuso/maxUC; mauso = mauso/maxUC; 100 this.th_ps.tuso = tuso; this.th_ps.mauso = mauso; } rt gn ta cn tnh c chung ln nht, c th ci t hm ny chung vi lp XL_PHANSO public int TimMaxUocChung(int a, int b) { while(a!=b) { if(a>b) a -= b; else b -= a; } return a; } Thc hin ci t mn hnh chnh (MainFrm)
Trong form chnh s thc hin khai bo 3 i tng x l phn s private PhanSo.XL_PHANSO xl_PhanSo1; private PhanSo.XL_PHANSO xl_PhanSo2; private PhanSo.XL_PHANSO xl_PhanSo3;
Thc hin khi to 3 i tng x l phn s va khai bo public MainFrm() { // // Required for Windows Form Designer support InitializeComponent(); xl_PhanSo1 = new XL_PHANSO(new LT_PHANSO("phanso1.xml"), tH_PHANSO1); 101 xl_PhanSo2 = new XL_PHANSO(new LT_PHANSO("phanso2.xml"), tH_PHANSO2); xl_PhanSo3 = new XL_PHANSO(new LT_PHANSO(""),tH_PHANSO3); } Vit hm x l cho cc nt chc nng trn form: Hm x l cho nt Cng private void btnCong_Click(object sender, System.EventArgs e) { XL_PHANSO kq = xl_PhanSo1 + xl_PhanSo2; xl_PhanSo3.CapNhat(kq); xl_PhanSo3.Ghi(ketqua.xml); xl_PhanSo3.RutGon(); } Hm x l cho nt Thoat private void btnThoat_Click(object sender, System.EventArgs e) { this.Close(); } To cc tp tin phanso1.xml, phanso2.xml, c nh dng nh v d trn. Thc hin bin dch v chy th chng trnh. Nhn xt : Thc hin ci t vi kin trc 3 lp s gip chng trnh d dng thay i, ti s dng li chng trnh. V d: TH_PHANSO khng th hin t s v mu s bng TextBox na m thay bng control khc (v d nh MyControl th cng khng nh hng, lc ch cn thay i code trong phn property t s v mu s m thi. public int tuso{ set{ this.MyControl.Value = value.ToString(); } get{ return int.Parse(this.MyControl.Value); } } public int mauso { set { this.MyControl.Value = value.ToString(); } get { return int.Parse(this.MyControl.Value); } } Khi khng lu tr bng XML m chuyn sang dng c s d liu th ta ch cn thay code phn LT_PHANSO, m khng cn thay i code phn TH_PHANSO, cng nh XL_PHANSO. 102 Ch : Khng ph thuc phng php lp trnh. Mi nghip v khng nht thit ch c gii quyt bi 3 i tng. Khng l mt kin trc siu vit. 4.2. Remoting 4.2.1. Gii thiu v Remoting .NET Remoting l g? - Trc ht .NET Remoting l mt k thut .NET c gii thiu t .NET framework 1.1. Cng vi .NET Webservice, .NET remoting l la chn cho gii php x l tnh ton t xa. .NET Remoting l mt k thut cho php mt i tng ny truy xut n mt i tng khc nm cc Application Domain khc nhau. V nu gii thch theo kiu bnh dn, ta c th s dng .NET Remoting gi mt chng trnh hoc mt service chy trn mt my vi tnh khc x l mt ci g v tr kt qu tnh ton li cho ta.
Hnh 4.1: .NET Remoting Overview .NET Remoting v Distributed COM - Vo nm mt ngn chn trm hi , ngi ta thng thc hin vic giao tip gia cc process bng cch s dng Distributed COM hay cn gi l DCOM. DCOM rt hu ch cho nhng chng trnh chy trn cc my tnh cng loi v nm trong cng mt mng. Tuy nhin, DCOM tr nn li thi v n khng th chy trn Internet. DCOM da trn mt tp giao thc m khng phi object no cng h tr v iu ny khin DCOM khng chy c trn nhng platform khc nhau. Ngoi ra, DCOM s dng nhiu port trong khi cc port y thng b chn bi firewall. Tt nhin m nhng port n hot ng c khng kh nhng l mt trong nhng phin phc. - .NET Remoting khc phc nhng yu km ca DCOM bng cch h tr nhiu giao thc khc nhau. .NET Remoting v Web Services - V kha cnh x l t xa th Web Services hon ton tng t nh .NET Remoting. Thm ch ngi ta c th lm cho .NET Remoting tr thnh 1 Web Services bng cch 103 host n trong IIS. Web Services cho php cc ng dng c th giao tip vi nhau m khng ph thuc platform, ngn ng lp trnh, Tuy nhin Web Services l mt mi trng stateless, c ngha l n khng lu li bt k trng thi g ca ln gi trc v n cng khng bit g v pha client ang thc hin request. Client v server Web Services ch c th trao i vi nhau bng cc thng ip SOAP. Nhng iu sau y l cc im khc nhau chnh gia .NET Remoting v Web Serices, chng cng l nhng nhn t ta chn la gia 2 cng ngh ny: ASP.NET Web Services ch c th c truy xut qua HTTP cn .NET Remoting c th c dng trn nhiu giao thc khc nhau nh TCP, HTTP. Web Services l mt mi trng stateless. Khi c mt request t pha client, s c mt object mi c to ra thc hin request trn server. Cn .NET Remoting li h tr nhiu la chn state management v c th thc hin nhiu request t mt client, ng thi c h tr callbacks. Web Services serialize cc i tng thnh XML bn trong SOAP message v v th c th truyn ti thng tin ca bt c thnh phn no min c th chuyn thnh XML. Cn i vi .NET Remoting th ty giao thc v nh dng message m n c th truyn i thng tin nh th no. Ngoi ra theo nh gii thiu th .NET Remoting c cho php i tng c truyn vo theo c kiu tham chiu(reference) v tham tr (value) Web services c th hot ng trn cc platform mi trng khc nhau trong khi .NET Remoting yu cu pha clients phi l .NET application. Channels - Trong k thut .NET Remoting th Channel c hiu nh l mt knh giao tip gia client v server. Mt object t client s thng qua Channel giao tip vi object pha server, Channel s truyn ti nhng message t hai pha. Nh gii thiu pha trn th c hai channel chnh l TcpChannel v HttpChannel tng ng vi cc giao thc TCP v HTTP. Ngoi ra, TcpChannel v HttpChannel u c kh nng extend thnh nhng Custom Channel ca bn. Lm sao to mt Object c th Remote c trong .NET Remoting? - Mt Object remote c ch l mt object thng thng nhng phi c inherit t MarshalByRefObject. on code sample hnh 4.2 l mt v d n gin v Remotable Object. i tng SampleObject trong hnh c mt s method n gin tr v php tnh tng, hiu, tch, thng ca hai s nguyn. Gi tr tr v ca hm l kiu s nguyn, kiu built-in ca .NET framework. Nu bn mun tr v kiu d liu bn t nh ngha, hoc mt instance ca class bn nh ngha th lp ca bn phi c khai bo vi attribute Serializable.
using System; public class SampleObject: MarshalByRefObject { public int Add(int a, int b) { int c = a + b; 104 return c; } public int Subtract(int a, int b) { int c = a - b; return c; } public int Multiply(int a, int b) { int c = a * b; return c; } public int Divide(int a, int b) { int c; if (b != 0) c = a / b; else c = 0; return c; } }
Hnh 4.2: Remotable Object Sample
To chng trnh Server host Remotable Object - K tip, chng ta cn to ra mt chng trnh server lng nghe nhng request t pha client. Trong v d ny chng ta s s dng TCP/IP channel. u tin chng ta to mt instance channel v ng k mt port tng ng cho n. Khi c mt Request t pha client, server s nhn request v Remote Object ca chng ta s thc thi Request ny. Trong .NET Remoting, c hai c ch to instance ca Remote Object ri t thc thi request: Singleton v Singlecall. Ty vo mc ch s dng, nhu cu ca chng trnh m server ca bn c th khai bo theo c ch WellKnownObjectMode.SingleCall, hay WellKnownObjectMode.Singleton. Khi khai bo Singleton, Remote Object s c sinh ra, thc thi request, reply li pha client v sau , object ny vn c lu li ch khng b hy i. n khi no process chy chng trnh server kt thc th instance ny mi b trnh ht rc Garbage Collector ht i. V ngc li, khi khai bo l SingleCall, Remote Object s c khi to v hy i i vi mi ln nhn request t pha client, c ch ny tng t nh m hnh .NET Web Service truyn thng. - Nu bn mun s dng .NET Remoting trong IIS th khng cn to mt chng trnh server nh th ny. V tt nhin, IIS ch h tr HttpChannel. Nu host 1 .NET Remoting bn trong IIS bn s mc nhin s dng c c ch Authentication ca IIS, ngc li nu lm mt chng trnh server host nh trn th bn phi ci t c ch Authentication ca ring mnh. host mt Remote Object bn trong IIS, trc tin phi to 1 Virtual Directory cho application, sau t on code ng k service bn trong event Application_Start (file global.asax) 105 - Trong v d ny, chng ta s khng s dng IIS m s to mt console application. C nhiu la chn khi khng s dng IIS, ta c th s dng console application, Win form application nhng trong thc t, ngi ta s s dng mt Windows Service lm. Cn Console application hay Winform Application thng ch dng minh ha. Trong v d ny, chng ta s s dng port 9999 cho may mn. C th mt chng trnh no trong my ca bn s dng port ny, nu b nh vy bn phi chn port khc. V sau cng, kim tra xem my bn ang lng nghe trn nhng port no (port no b s dng) th ta dng lnh netstat a trong command prompt. - Cn by gi, hy xem mt console application project vi 1 class tn l SampleSerrver. Trong project ny ti thm reference ti System.Runtime.Remoting vo trong project n c th chy c. using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; public class Server { public static int Main() { TcpChannel chan = new TcpChannel(9999); ChannelServices.RegisterChannel(chan, false); RemotingConfiguration.RegisterWellKnownServiceType(typeof(SampleObject) , "SampleNetRemoting", WellKnownObjectMode.SingleCall); Console.WriteLine("Hit <enter> to exit..."); Console.ReadLine(); } } Hnh 4. 3: Sample Server host Remotable Object
To chng trnh client s dng Remote Object. - Chng trnh client trong v d ny cng kh n gin, n s connect vo server, to mt instance ca Remote Object v excute method tnh tng, hiu, tch, thng. - Cc bn lu rng trong c chng trnh client v chng trnh server u phi reference ti class SampleObject. Client s gi method ca instance SampleObject, nhng server s thc thi x l n ch khng phi pha client. using System; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Http; public class Client { 106 public static int Main (string[] argv) { TcpChannel chan = new TcpChannel(); ChannelServices.RegisterChannel(chan, false); SampleObject obj = (SampleObject)Activator.GetObject( typeof(SampleObject), "tcp://localhost:9999/SampleNetRemoting"); if (obj == null) System.Console.WriteLine("Could not locate server"); else { int a = Convert.ToInt32(argv[0]); int b = Convert.ToInt32(argv[1]); int c = obj.Add(a, b); Console.WriteLine("a + b = {0}", c); c = obj.Subtract(a, b); Console.WriteLine("a - b = {0}", c); c = obj.Multiply(a, b); Console.WriteLine("a * b = {0}", c); c = obj.Divide(a, b); Console.WriteLine("a / b = {0}", c); } Console.ReadKey(); } } Hnh 4: Sample Client Application
Test th chng trnh - Trc tin chy chng trnh server, bn s thy message Press the enter key to exit trong ca s console. Nh vy server ca bn ang lng nghe trn port 9999. By gi bn hy chy chng trnh client v s nhn thy kt qu tr v trn mn hnh. Bn c th chy nhiu client cng request n 1 server nhng khng th chy nhiu server. Bn c th copy chng trnh server sang mt my ca bn mnh v nh chy th, cn bn sa li chng trnh client, sa localhost thnh IP ca my bn mnh v chy th thy kt qu. Tm tt: - V d trn s dng code C# khai bo cc cu hnh cho server v client tuy nhin .NET Remoting cho php ta cu hnh trc trong file config (App.config). Cc bn c th tham kho mt s resource pha di bit cch lm. - .NET Remoting l mt trong nhng k thut tin li cho nhng chng trnh dng Distributed Computing. Cch s dng n phc tp hn Web Service tuy nhin nu bn 107 mun tng performance th .NET Remoting vi Singleton v TCP channel s l la chn rt tt. - Vi s ra i ca .NET Framework 3.x, Microsoft gii thiu nn tng mi hn cho cc k thut RPC, l WCF mnh hn .NET Remoting rt nhiu. 4.2.2. Khai bo, ci t v ng k giao din t xa cho chng trnh c tnh kh chuyn cao thay v ngi ta xy dng lp Remote Object nh v d trn chng ta khai bo mt giao din l lp Remote Object v trong chng trnh pha Server ta s ci t giao din ny v ng k giao din t xa. Nh vy trin khai mt h thng Remoting ta c 3 chng trnh: Giao din Remote Object, chng trnh Server trin khai giao din v ng k giao din t xa, chng trnh Client triu gi phng thc t xa. - Khai bo giao din t xa - Ci t v ng k giao din t xa 4.2.3. Triu gi phng thc t xa - Chng trnh pha Client chng ta triu gi phng thc c cung cp bi giao din t xa c ng k v cung cp bi Server 4.3. Web Services 4.3.1. Gii thiu v Web Services 1. Web Service l g? Web service l mt Modul chng trnh cung cp chc nng ca cc ng dng cho php triu gi v truy cp t xa thng qua Internet. Web service s dng cc chun ca Internet nh XML v HTTP. Vic s dng Web service ph thuc nhiu vo s chp nhn ca XML, mt ngn ng m t d liu mi dng truyn ti d liu thng qua Web. Bt k mt Web service no cng c th c s dng, hoc l trong ng dng cc b hoc truy cp t xa qua Internet bi nhiu ng dng. Do c kh nng truy cp qua cc giao din chun m mt Web service cho php nhiu h thng khc nhau cng lm vic vi nhau nh mt tin trnh duy nht trn Web. 2. Vai tr ca Web service Web service ra i m ra mt hng mi cho vic pht trin cc ng dng trn Internet. Web services tm dch l cc dch v trn web. Cng ngh web services ra i l mt cuc cch mng ha cch thc hot ng ca cc dch v B2B v B2C. Web services kt hp s dng nhiu cng ngh khc nhau cho php hai ng dng cng ngn ng, c lp h iu hnh trao i c vi nhau thng qua mi trng mng Internet. Tuy nhin nhng cng ngh s dng y khng nht thit phi l nhng cng ngh mi. y l im khc bit ca web services so vi cc cng ngh khc, chnh l kh nng kt hp cc cng ngh c nh l XML, SOAP, WSDL, UDDI to ra cc service, c im ny lm ni bt vai tr ca web services. 108 Web Service c thit k nhm cung cp mt c ch cho php cc chng trnh giao tip vi nhau qua Internet (s dng cc giao thc Internet nh HTTP GET, HTP POST v SOAP). 3. c im Web service - Web service cho php client v server tng tc c vi nhau mc d trong nhng mi trng khc nhau. - Web Service th c dng m v da vo cc tiu chun XML v HTTP l nn tng k thut cho web service. Phn ln k thut ca web service c xy dng l nhng d n ngun m. Bi vy chng c lp v vn hnh c vi nhau. - Web Service th rt linh ng: V vi UDDI v WSDL, th vic m t v pht trin web service c th c t ng ho. - Web service c xy dng trn nn tng nhng cng ngh c chp nhn. - Web service c dng modul. - Web service c th c cng b (publish) v gi thc hin qua mng. Ngy nay web service c s dng rt nhiu trong nhng lnh vc khc nhau ca cuc sng nh: - Dch v chn lc v phn loi tin tc: l nhng h thng th vin kt ni n cc web portal tm kim cc thng tin t cc nh xut bn c cha nhng kho mun tm. - Dch v hin th danh sch a nhc dnh cho cc cng ty thu thanh. - ng dng i l du lch c nhiu gi v i du lch khc nhau do c chn la phc v ca nhiu hng hng khng. - Bng tnh ton chnh sch bo him dng cng ngh Excel/COM vi giao din web. - Thng tin thng mi bao gm nhiu ni dung, nhiu mc tin nh: d bo thi tit, thng tin sc kho, lch bay, t gi c phiu, - Nhng giao dch trc tuyn cho c B2B v B2C nh: t v my bay, lm giao ko thu xe. - H thng thng tin dng java tnh ton t gi chuyn i gia cc loi tin t. H thng ny s c cc ng dng khc dng nh mt web service. 4. Kin trc Web service Kin trc ca Web service bao gm cc tng nh sau: 109
Hnh 1: Kin trc Web service
Trong bao gm cc tng nh sau: - Tng vn chuyn: c nhim v truyn thng ip gia cc ng dng mng, bao gm nhng giao thc nh HTTP, SMTP, FTP, JSM v gn y nht l giao thc thay i khi m rng (Blocks Extensible Exchange Protocol- BEEP). - Tng giao thc tng tc dch v ( Service Communication Protocol) vi cng ngh chun l SOAP. SOAP l giao thc nm gia tng vn chuyn v tng m t thng tin v dch v, SOAP cho php ngi dng triu gi mt service t xa thng qua mt message XML. - Tng m t dch v (Service Description) vi cng ngh chun l WSDL v XML. WSDL l mt ngn ng m t giao tip v thc thi da trn XML. Web service s dng ngn ng WSDL truyn cc tham s v cc loi d liu cho cc thao tc, cc chc nng m web service cung cp. - Tng dch v ( Service): cung cp cc chc nng ca service. - Tng ng k dch v (Service Registry) vi cng ngh chun l UDDI. UDDI dng cho c ngi dng v SOAP server, n cho php ng k dch v ngi dng c th gi thc hin service t xa qua mng, hay ni cch khc mt service cn phi c ng k cho php cc client c th gi thc hin - Bn cnh cho cc service c tnh an ton, ton vn v bo mt thng tin trong kin trc web service chng ta c thm cc tng Policy, Security, Transaction, Management gip tng cng tnh bo mt, an ton v ton vn thng tin khi s dng service. 4.3.2. Giao thc SOAP 110 SOAP l ch vit tt ca cm t Simple Object Access Protocol Giao thc truy cp i tng n gin, nhng vi s xem xt mi nht th, SOAP s khng cn l mt t vit tt na. Chun SOAP ghi nhn XML c th hin th no bn trong ti liu SOAP, lm th no ni dung ca thng ip c truyn ti, v lm th no thng ip c x l c hai pha gi v nhn. SOAP cng cung cp mt tp cc t vng chun. Cc thut ng: Nh bt k cng ngh no, SOAP cng c tp cc thut ng ca ring n. C nhiu thut ng c s dng thng xuyn m t cc kha cnh khc nhau ca chun SOAP. Nhiu lp trnh vin dng cc thut ng ny m khng tht s hiu ngha ca n. hiu tht s cc khi nim i hi phi tn mt thi gian hiu ngha ca tng thut ng v lm th no p dng cho c chun SOAP v mt Web Services thc th Ch : Chun SOAP khng ch l chun XML m chun ny cn bao gm cc thng ip SOAP c hnh vi nh th no, cc phng tin vn chuyn khc nhau, cch m cc li c x l.. S truyn ti d liu SOAP Binding Thut ng m t lm th no mt thng ip SOAP tng tc c vi mt giao thc vn chuyn nh HTTP, SMTP hay FTP di chuyn trn Internet. iu quan trng l SOAP di chuyn bng mt giao thc chun lin lc vi cc sn phm Web Services khc. Trc SOAP, nhiu ngi pht trin to ra cc phng php ca ring h chuyn ti mt ti liu XML trn mng. Cc cch ny vn hot ng tt trong phm vi mt nhm c th. Tuy nhin khi bn cn lm vic vi mt nhm khc trong hay bn ngoi cng ty th iu ny tr nn kh khn v phi hun luyn v c th thay i lm vic vi vic truyn ti ti liu XML m h ang s dng. Bng cch s dng mt ti liu XML chun trn cc giao thc chun, cng vic cn lm khi cng tc vi nhau s c gim thiu ti a SOAP Message Exchang Pattern (MEP) Thut ng m t lm th no m mt ti liu SOAP trao i gia pha my khch v ch. Thng ip SOAP s hu mt lin kt, nh l HTTP, n c th truyn trn Internet. Vic ni chuyn gia my khch v ch, y l cc nt, xc nh cc hnh ng m c hai pha thc hin. Nhc li SOAP l mt XML ng gi RPC. V th, MEP hon ton l yu cu v phn hi gia my khch v ch (hay cc nt khc). Nh vy nu c nhu cu lin lc gia cc nt th vic ny c thc hin bng nhiu yu cu v phn hi hon tt vic truyn thng ip. Cch ny khc hn vi cc cng ngh i tng t xa khc nh CORBA, cng ngh c thc hin ch trong mt kt ni. SOAP Application Mt ng dng SOAP n gin l mt ng dng dng SOAP theo mt vi cch khc nhau. Vi ng dng hon ton da trn chun SOAP, nh l Web Services c phiu, hoc dng chun SOAP nhn m v cc cp nht ca phn mm. Ch l mt ng dng c th to, s dng hoc l nt trung gian ca Web Services. SOAP Node Trch nhim ca mt nt c th bao gm gi, nhn, x l hoc truyn ti li mt thng ip SOAP. Mt nt ch l mt phn nh ca phn mm, x l mt ti liu SOAP ph thuc vo 111 vai tr ca n. Bn cnh vic truyn d liu, mt nt c trch nhim m bo thng tin XML trong ti liu SOAP phi ng ng php theo chun SOAP. SOAP Role Mt vai tr ca SOAP nh ngha mt nt c th hot ng nh th no. N c th l nt gi, nhn hoc nt trung gian. SOAP Sender Nt gi l nt gi yu cu SOAP. Nu bn ngh n v d ca ng dng khch ch th khi ng dng khch thc hin yu cu, n gi thng ip ti ng dng ch yu cu vi thng tin. SOAP Receiver Ngc li vi SOAP sender l nt nhn. SOAP Intermediary Mt nt trung gian c th xem mt thng ip SOAP v tng tc trn vi phn thng tin ca thng ip, v chuyn n v tr k tip ca thng ip. Mt nt trung gian thng hot ng nh mt router. Mt router s xem xt thng tin ca gi tin chuyn trn mng, tm im k tip ca gi tin v chuyn gi tin n . Message Path Mt thng ip SOAP di chuyn t pha bn gi n pha bn nhn thng ip thng qua nhiu nt trung gian. Tuyn ng i ca thng ip c gi l mt Message Path. Initial SOAP Sender Nt gi yu cu SOAP u tin l nt gi SOAP ban u. SOAP Feature Mt c im SOAP l mt phn chc nng ca phn mm h tr chc nng SOAP. Cc thut ng lin quan n XML Chun SOAP cng nh ngha mt tp nh cc phn t XML ng gi d liu c truyn gia cc nt. Tht s ch c vi phn t v phn thn ca thng ip c th khc nhau ph thuc vo ci t. S uyn chuyn ny c cho php bi chun SOAP. SOAP Message y l ti liu XML c truyn bi mt nt SOAP gi hoc nhn. Mt nt gi hoc nt khch to ra mt ti liu XML cha thng tin m pha bn khch cn t pha ch. Mt khi ti liu c truyn, pha bn ch phn gii thng tin trong ti liu truy xut cc gi tr khc nhau v to mt thng ip SOAP mi phn hi. SOAP Envelope y l phn t gc ca ti liu SOAP XML. Ti liu SOAP cha nhiu nh ngha khng gian tn (namespace) nhng cc phn t lin quan ti thng ip SOAP s c ENV: l tip u ng. SOAP Header 112 Phn u ca mt thng ip SOAP cha mt khi thng tin u trong ti liu XML nh tuyn v x l thng ip SOAP. D liu ny tch ri khi phn thn ca ti liu c cha thng tin lin quan n i tng c gi. SOAP Header Block Phn u ca SOAP cha nhiu phn gii hn hay l nhiu khi thng tin c mt khi thng tin ca phn u. Nhng khi thng tin ca phn u ny cha thng tin v cc nt trung gian v mt nt cn bit nt k tip thng ip c gi n. SOAP Body Phn thn ca SOAP tht s cha thng tin ca i tng x l thng tin. Phn thn sau khi c phn tch s tr thnh i tng. i tng x l thng tin v kt qu c t trong phn thn ca ti liu tr v. SOAP Fault y l mt phn thng tin ca SOAP cha thng tin n bt k li g xy ra ti mt nt SOAP.
4.3.3. Xy dng Web Services - To mt Web Services project
- To Web Method 113
- Chy th Web Services danh sch cc hm s c lit k
- Chn hm Add 114
- Sau khi nhp cc tham s vo, nhn Invoke. Kt qu s xut hin
4.3.4. Triu gi Web Services t ng dng .NET, Java v cc ngn ng khc - Sau khi xy dng Web Server song ta c th triu gi n t mt ng dng khc - To mt Window Form 115
- Add Web Reference
- To mn hnh:
116 - Vit hm x l nt nhn:
- Chy th ng dng ta c kt qu:
4.4 Tho lun v cc ng dng phn tn
4.5. Bi tp p dng 1. Vit chng trnh Chat s dng cng ngh Web Services 2. Vit chng trnh Calculator bng cng ngh Web Services 3. Vit chng trnh qun l FileManager bng cng ngh Web Services. 117 TI LIU THAM KHO
1. Richard Blum, C# Network Programming, 2003 2. Fiach Reid, Network programming in NET with C# and VB.NET, Digital Press, 2003 3. Bi ging Nhp mn Cng ngh phn mm, i hc KHTN 4. Bi ging Xy dng phn mm hng i tng, i hc KHTN 5. Bi ging Lp trnh truyn thng, i hc Cn Th 6. Bi ging Cng ngh .NET, Khoa CNTT i hc SPKT Hng Yn 7. Bi ging Java Nng cao, Khoa CNTT- i hc SPKT Hng Yn 8. Cc v d ti Website: www.java2s.com