Lap trinhmang(socket)c#

117
1 CHƯƠNG 1: CÁC KIẾN THỨC CƠ BẢN VỀ MẠNG MÁY TÍNH.......................................3 1.1. Mô hình tham khảo 7 tầng OSI ........................................................................................3 1.2. Họ giao thức TCP/IP........................................................................................................5 1.3. So sánh giữa hai giao thức TCP và UDP .........................................................................6 1.4. Cổng giao thức .................................................................................................................7 1.5. ðịa chỉ IP, các ñịa chỉ IP dành riêng................................................................................7 1.6. ðịa chỉ tên miền: loại A, loại MX.. .................................................................................8 1.7. Một số giao thức ở tầng ứng dụng: HTTP, SMTP, POP3, FTP... ...................................8 CHƯƠNG 2: LẬP TRÌNH MẠNG TRONG .NET FRAMEWORK ........................................9 2.1. Socket hướng kết nối (TCP Socket) ................................................................................9 2.1.1. Giới thiệu về NameSpace System.Net và System.Net.Sockets ..............................10 2.1.2. Viết chương trình cho phía máy chủ.......................................................................11 2.1.3. Viết chương trình cho phía máy khách ...................................................................13 2.1.4. Sử dụng các luồng nhập xuất với Socket ................................................................14 2.2. Socket không hướng kết nối (UDP Socket) ...................................................................17 2.2.1. Viết chương trình cho phía máy chủ.......................................................................17 2.2.2. Viết chương trình cho phía máy khách ...................................................................18 2.2.3. Sử dụng lớp System.IO.MemoryStream ñể tạo vùng ñệm nhập xuất.....................20 2.3. Sử dụng các lớp hỗ trợ ñược xây dựng từ lớp Soket .....................................................20 2.3.1. Lớp TCPClient ........................................................................................................21 2.3.2. Lớp TCPListener ....................................................................................................22 2.3.3. Lớp UDPClient .......................................................................................................24 2.4. Socket không ñồng bộ....................................................................................................26 2.4.1. Mô hình xử lý sự kiện của windows .......................................................................26 2.4.2. Sử dụng Socket không ñồng bộ ..............................................................................27 2.4.3. Ví dụ về Socket không ñồng bộ ..............................................................................28 2.4.4. Sử dụng các phương thức Non-blocking ................................................................35 2.5. Sử dụng Thread trong các ứng dụng mạng ....................................................................39 2.5.1. Sử dụng Thread trong chương trình .Net ................................................................40 2.5.2. Sử dụng Thread trong các chương trình Server ......................................................41 2.5.3. Sử dụng Thread ñể gửi/nhận dữ liệu .......................................................................41 2.5.4. Sử dụng ThreadPool trong các chương trình .Net ..................................................43 2.5.5. Sử dụng ThreadPool trong các chương trình Server...............................................47 2.6. Kỹ thuật IP Multicasting ................................................................................................48 2.6.1. Broadcasting là gì?..................................................................................................48 2.6.2. Sử dụng Broadcasting ñể gửi dữ liệu ñến nhiều máy trong mạng cục bộ ..............48 2.6.3. Multicasting là gì? ..................................................................................................49 2.6.4. Socket Multicasting trong .Net ...............................................................................50 2.7 Bài tập áp dụng ...............................................................................................................53 CHƯƠNG 3: XÂY DỰNG ỨNG DỤNG MẠNG ...................................................................55 3.1. Giao thức ICMP .............................................................................................................55 3.1.1. Sử dụng Raw Socket ...............................................................................................55 3.1.2. Sử dụng giao thức ICMP và Raw Socket ñể xây dựng chương trình Ping .............57 3.1.3. Sử dụng giao thức ICMP và Raw Socket ñể xây dựng chương trình TraceRoute .58 3.2. Giao thức SMTP, POP3 .................................................................................................60 3.2.1. Cơ bản về hệ thống Mail và giao thức SMTP, POP3 .............................................60 3.2.2. Cài ñặt SMTP, POP3 Client/Server ........................................................................60 3.3. Giao thức HTTP.............................................................................................................67 3.3.1. Cơ bản về giao thức HTTP .....................................................................................67 3.3.2. Cài ñặt HTTP Client/Server ....................................................................................68 3.4. Giao thức FTP ................................................................................................................74 3.4.1. Cơ bản về giao thức FTP ........................................................................................74 3.4.2. Cài ñặt FTP Client/Server .......................................................................................84

Transcript of Lap trinhmang(socket)c#

1. 1 CHNG 1: CC KI N TH C C B N V M NG MY TNH.......................................3 1.1. M hnh tham kh o 7 t ng OSI........................................................................................3 1.2. H giao th c TCP/IP........................................................................................................5 1.3. So snh gi a hai giao th c TCP v UDP.........................................................................6 1.4. C ng giao th c.................................................................................................................7 1.5. a ch IP, cc a ch IP dnh ring................................................................................7 1.6. a ch tn mi n: lo i A, lo i MX.. .................................................................................8 1.7. M t s giao th c t ng ng d ng: HTTP, SMTP, POP3, FTP... ...................................8 CHNG 2: L P TRNH M NG TRONG .NET FRAMEWORK ........................................9 2.1. Socket h ng k t n i (TCP Socket) ................................................................................9 2.1.1. Gi i thi u v NameSpace System.Net v System.Net.Sockets..............................10 2.1.2. Vi t chng trnh cho pha my ch .......................................................................11 2.1.3. Vi t chng trnh cho pha my khch...................................................................13 2.1.4. S d ng cc lu ng nh p xu t v i Socket................................................................14 2.2. Socket khng h ng k t n i (UDP Socket)...................................................................17 2.2.1. Vi t chng trnh cho pha my ch .......................................................................17 2.2.2. Vi t chng trnh cho pha my khch...................................................................18 2.2.3. S d ng l p System.IO.MemoryStream t o vng m nh p xu t.....................20 2.3. S d ng cc l p h tr c xy d ng t l p Soket .....................................................20 2.3.1. L p TCPClient........................................................................................................21 2.3.2. L p TCPListener ....................................................................................................22 2.3.3. L p UDPClient .......................................................................................................24 2.4. Socket khng ng b ....................................................................................................26 2.4.1. M hnh x l s ki n c a windows.......................................................................26 2.4.2. S d ng Socket khng ng b ..............................................................................27 2.4.3. V d v Socket khng ng b ..............................................................................28 2.4.4. S d ng cc phng th c Non-blocking ................................................................35 2.5. S d ng Thread trong cc ng d ng m ng....................................................................39 2.5.1. S d ng Thread trong chng trnh .Net................................................................40 2.5.2. S d ng Thread trong cc chng trnh Server......................................................41 2.5.3. S d ng Thread g i/nh n d li u.......................................................................41 2.5.4. S d ng ThreadPool trong cc chng trnh .Net ..................................................43 2.5.5. S d ng ThreadPool trong cc chng trnh Server...............................................47 2.6. K thu t IP Multicasting................................................................................................48 2.6.1. Broadcasting l g?..................................................................................................48 2.6.2. S d ng Broadcasting g i d li u n nhi u my trong m ng c c b ..............48 2.6.3. Multicasting l g? ..................................................................................................49 2.6.4. Socket Multicasting trong .Net ...............................................................................50 2.7 Bi t p p d ng ...............................................................................................................53 CHNG 3: XY D NG NG D NG M NG...................................................................55 3.1. Giao th c ICMP.............................................................................................................55 3.1.1. S d ng Raw Socket...............................................................................................55 3.1.2. S d ng giao th c ICMP v Raw Socket xy d ng chng trnh Ping.............57 3.1.3. S d ng giao th c ICMP v Raw Socket xy d ng chng trnh TraceRoute .58 3.2. Giao th c SMTP, POP3.................................................................................................60 3.2.1. C b n v h th ng Mail v giao th c SMTP, POP3 .............................................60 3.2.2. Ci t SMTP, POP3 Client/Server........................................................................60 3.3. Giao th c HTTP.............................................................................................................67 3.3.1. C b n v giao th c HTTP .....................................................................................67 3.3.2. Ci t HTTP Client/Server....................................................................................68 3.4. Giao th c FTP................................................................................................................74 3.4.1. C b n v giao th c FTP ........................................................................................74 3.4.2. Ci t FTP Client/Server.......................................................................................84 2. 2 3.5. DNS (Domain Name Server).........................................................................................88 3.5.1. V n phn gi i tn mi n ......................................................................................88 3.5.2. Tri n khai DNS MX (Mail Exchange) ...................................................................89 3.6 Th o lu n v cc ng d ng khc th ng g p .................................................................93 3.7 Bi t p p d ng ...............................................................................................................93 CHNG 4: XY D NG NG D NG NHI U L P ..........................................................94 4.1. M hnh 2 l p (two tier), 3 l p (three tier) v n l p. .....................................................94 4.2. Remoting........................................................................................................................98 4.2.1. Gi i thi u v Remoting.........................................................................................102 4.2.2. Khai bo, ci t v ng k giao di n t xa........................................................102 4.2.3. Tri u g i phng th c t xa .................................................................................107 4.3. Web Serive...................................................................................................................107 4.3.1. Gi i thi u v Web Serives ....................................................................................107 4.3.2. Giao th c SOAP ...................................................................................................109 4.3.3. Xy d ng Web Services........................................................................................112 4.3.4. Tri u g i Web Services t ng d ng .NET, Java v cc ngn ng khc .............114 4.4 Th o lu n v cc ng d ng phn tn ............................................................................116 4.5. Bi t p p d ng ............................................................................................................116 3. 3 CHNG 1: CC KI N TH C C B N V M NG MY TNH 1.1. M hnh tham kh o 7 t ng OSI M hnh k t n i h th ng m c T ch c qu c t v tiu chu n ho ISO (International Organizaiton for Standardization) a ra nh m cung c p m t m hnh chu n cho cc nh s n xu t v cung c p s n ph m vi n thng p d ng theo pht tri n cc s n ph m vi n thng. t ng m hnh ho c t o ra cn nh m h tr cho vi c k t n i gi a cc h th ng v modun ho cc thnh ph n ph c v m ng vi n thng. a. Ch c nng c a m hnh OSI: - Cung c p ki n th c v ho t ng c a k t n i lin m ng - a ra trnh t cng vi c thi t l p v th c hi n m t giao th c cho k t n i cc thi t b trn m ng. M hnh OSI cn c m t s thu n l i sau : - Chia nh cc ho t ng ph c t p c a m ng thnh cc ph n cng vi c n gi n. - Cho php cc nh thi t k c kh nng pht tri n trn t ng modun ch c nng. - Cung c p cc kh nng nh ngha cc chu n giao ti p c tnh tng thch cao plug and play v tch h p nhi u nh cung c p s n ph m. b. C u trc m hnh OSI: M hnh OSI g m 7 l p (level), m i l p th c hi n cc ch c nng ring cho ho t ng k t n i m ng. Hnh 1-1 M t b y l p OSI. 4 l p u nh ngha cch th c cho u cu i thi t l p k t n i v i nhau trao i d li u. 3 l p trn dng pht tri n cc ng d ng u cu i k t n i v i nhau v ng i dng. Aplication PresentationApplication (Upper Layer) Session Transport Layer Network Layer Data Link Physical Data Lower Layer Cc l p trn 3 l p trn cng c a m hnh OSI th ng c g i l cc l p ng d ng (Application layers) hay cn g i l cc l p cao. Cc l p ny th ng lin quan t i giao ti p v i ng i dng, nh d ng c a d li u v phng th c truy nh p cc ng d ng . Hnh 1-2 M t cc l p trn v cung c p thng tin v i cc ch c nng c a n qua v d : - L p ng d ng: ch c nng giao Telnet, HTTP 4. 4 Application ti p gi a ng i s d ng v cc chng trnh ng d ng Presentation - L p trnh by: cch th c chu n ho d li u v trnh by s li u - C ch c nng c bi t l m ho d li u ng i s dung ASSCII EBCDIC JPEC Session - L p phin: thi t l p, duy tr v hu b m t phin lm vi c NFS, SQL Transport Layer Network Layer Data Link Physical - Application layer : y l l p cao nh t trong m hnh. N l ni m ng i s d ng ho c k t n i cc chng trnh ng d ng v i cc th t c cho php truy nh p vo m ng. - Presentation layer : L p presentation cung c p cc m v ch c nng chuy n i m c cung c p b i l p ng d ng. Cc ch c nng m b o r ng d li u t l p ng d ng trong m t h th ng c th c c b i l p ng d ng c a m t h th ng khc. VD : dng m ho d li u t l p ng d ng : nh m ho nh jpeg , gif. M cho php ta c th hi n ln trang web . - Session layer : c s d ng thi t l p, duy tr v k t thc phin lm vi c gi a cc l p presentation. Vi c trao i thng tin l p ny bao g m yu c u d ch v v p ng yu c u c a cc ng d ng trn thi t b khc. Cc l p d i. 4 l p d i c a m hnh OSI s d ng nh ngha lm th no d li u c truy n i trong cc dy n i v t l, cc thi t b m ng v i n tr m u cu i cu i cng l n cc l p ng d ng. Qu n sch ny ta ch quan tm n 4 l p cu i. V s xem xt t ng l p m t cch chi ti t giao thi p gi a cc l p trong m hnh OSI: S d ng phng php protocal stack k t n i gi a hai thi t b trong m ng. Protocal stack l m t t p h p cc quy nh dng nh ngha lm th no d li u truy n qua m ng. V d v i : TCP/IP m i Layer cho php d li u truy n qua. Cc l p trao i cc thng tin cung c p cu c lin l c gi a hai thi t b trong m ng. Cc l p giao ti p v i nhau s d ng Protocal Data Unit (PDU). Thng tin i u khi n c a PDU c thm 5. 5 vo v i d li u l p trn. V thng tin i u khi n ny n m trong tr ng g i l tr ng 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 th c TCP/IP Cc t ng c a giao th c TCP/IP so v i c c t ng c a m hnh OSI Application: Xc nh n quy n, nn d li u v cc d ch v cho ng i dng Transport: X l d li u gi a cc h th ng va cung c p vi c truy c p m ng cho cc ng d ng Network: Tm ng cho cc packet 6. 6 Link: M c OS ho c cc thi t b giao ti p m ng trn m t my tnh M t s i m khc nhau c a TCP/IP v m hnh OSI + L p ng d ng trong TCP/IP x l ch c nng c a l p 5,6,7 trong m hnh OSI + L p transport trong TCP/IP cung c p c ch UDP truy n khng tin c y, transport trong OSI lun m b o truy n tin c y + TCP/IP l m t t p c a cc protocols (m t b giao th c) + TCP/IP xy d ng tr c OSI Quy trnh ng gi d li u trong m hnh TCP/IP nh sau: 1.3. So snh gi a hai giao th c TCP v UDP 7. 7 1.4. C ng giao th c L m t s nm trong kho ng 1..65535 dng phn bi t gi a 2 ng d ng m ng v i nhau g n v i a ch IP v Socket M t s c ng v cc giao th c thng d ng: + FTP: 21 + Telnet: 23 + SMTP: 25 + POP3: 110 + HTTP:80 1.5. a ch IP, cc a ch IP dnh ring Reverved for future use01111Class E Multicast address0111Class D HostidNetid011Class C HostidNetid01Class B HostidNetid0Class A 2416843210 Reverved for future use01111Class E Multicast address0111Class D HostidNetid011Class C HostidNetid01Class B HostidNetid0Class A 2416843210 8. 8 1.6. a ch tn mi n: lo i A, lo i MX.. 1.7. M t s giao th c t ng ng d ng: HTTP, SMTP, POP3, FTP... - Chng ta s nghin c u chi ti t cc giao th c ny chng 3 9. 9 CHNG 2: L P TRNH M NG TRONG .NET FRAMEWORK 2.1. Socket h ng k t n i (TCP Socket) Socket l m t giao di n l p trnh ng d ng (API) m ng Thng qua giao di n ny chng ta c th l p trnh i u khi n vi c truy n thng gi a hai my s d ng cc giao th c m c th p l TCP, UDP Socket l s tr u t ng ho m c cao, c th t ng t ng n nh l thi t b truy n thng hai chi u g i nh n d li u gi a hai my tnh v i nhau. Cc lo i Socket Socket h ng k t n i (TCP Socket) Socket khng h ng k t n i (UDP Socket) Raw Socket c i m c a Socket h ng k t n i C 1 ng k t n i o gi a 2 ti n trnh M t trong 2 ti n trnh ph i i ti n trnh kia yu c u k t n i. C th s d ng lin l c theo m hnh Client/Server Trong m hnh Client/Server th Server l ng nghe v ch p nh n m t yu c u k t n i M i thng i p g i u c xc nh n tr v Cc gi tin chuy n i tu n t c i m c a Socket khng h ng k t n i Hai ti n trnh lin l c v i nhau khng k t n i tr c ti p Thng i p g i i ph i km theo a ch c a ng i nh n Thng i p c th g i nhi u l n Ng i g i khng ch c ch n thng i p t i tay ng i nh n Thng i p g i sau c th n ch tr c thng i p g i tr c . S hi u c ng c a Socket 10. 10 c th th c hi n cc cu c giao ti p, m t trong hai qu trnh ph i cng b s hi u c ng c a socket m mnh s d ng. M i c ng giao ti p th hi n m t a ch xc nh trong h th ng. Khi qu trnh c gn m t s hi u c ng, n c th nh n d li u g i n c ng ny t cc qu trnh khc. Qu trnh cn l i cng yu c u t o ra m t socket. 2.1.1. Gi i thi u v NameSpace System.Net v System.Net.Sockets Cung c p m t giao di n l p trnh n gi n cho r t nhi u cc giao th c m ng. C r t nhi u l p l p trnh Ta quan tm l p IPAdress, IPEndPoint, DNS, L p IPAdress M t s Field c n ch : Any: Cung c p m t a ch IP ch ra r ng Server ph i l ng nghe trn t t c cc Card m ng Broadcast: Cung c p m t a ch IP qu ng b Loopback: Tr v m t a ch IP l p AdressFamily: Tr v h a ch c a IP hi n hnh L p IPAddress M t s phng th c c n ch : Phng th c kh i t o IPAddress(Byte[]) IPAddress(Int64) IsLoopback: Cho bi t a ch c ph i a ch l p khng Parse: Chuy n IP d ng xu v IP chu n ToString: Tr a ch IP v d ng xu TryParse: Ki m tra IP d ng xu c h p l khng? L p IPEndPoint M t s phng th c c n ch : Phng th c kh i t o IPEndPoint (Int64, Int32) IPEndPoint (IPAddress, Int32) Create: T o m t EndPoint t m t a ch Socket ToString : Tr v a ch IP v s hi u c ng theo khun d ng aCh : C ng, v d : 192.168.1.1:8080 L p DNS M t s thnh ph n c a l p: HostName: Cho bi t tn c a my c phn gi i GetHostAddress: Tr v t t c IP c a m t tr m GetHostEntry: Gi i p tn ho c a ch truy n vo v tr v i t ng IPHostEntry 11. 11 GetHostName: L y v tn c a my tnh c c b NameSpace System.Net.Sockets M t s l p hay dng: TcpClient, UdpClient, TcpListener, Socket, NetworkStream, t o ra Socket Socket(AddressFamily af, SocketType st, ProtocolType pt) SocketType Protocoltype Description Dgram Udp Connectionless communication Stream Tcp Connection-oriented communication Raw Icmp Internet Control Message Protocol Raw Raw Plain IP packet communication using System.Net; using System.Net.Sockets; class SockProp { public static void Main() { IPAddress ia = IPAddress.Parse("127.0.0.1"); IPEndPoint ie = new IPEndPoint(ia, 8000); Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Console.WriteLine("AddressFamily: {0}", test.AddressFamily); Console.WriteLine("SocketType: {0}", test.SocketType); Console.WriteLine("ProtocolType: {0}", test.ProtocolType); Console.WriteLine("Blocking: {0}", test.Blocking); test.Blocking = false; Console.WriteLine("new Blocking: {0}", test.Blocking); Console.WriteLine("Connected: {0}", test.Connected); test.Bind(ie); IPEndPoint iep = (IPEndPoint)test.LocalEndPoint; Console.WriteLine("Local EndPoint: {0}", iep.ToString()); test.Close(); Console.ReadKey(); } } 2.1.2. Vi t chng trnh cho pha my ch Vi t chng trnh cho pha my ch T o m t Socket Lin k t v i m t IPEndPoint c c b L ng nghe k t n i Ch p nh n k t n i G i nh n d li u theo giao th c thi t k 12. 12 ng k t n i sau khi hon thnh v tr l i tr ng thi l ng nghe ch k t n i m i Vi t 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(); //G i nh n d li u theo giao th c thi t 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. 13 data = Encoding.ASCII.GetBytes(s); client.Send(data, data.Length, SocketFlags.None); } client.Shutdown(SocketShutdown.Both); client.Close(); server.Close(); } } 2.1.3. Vi t chng trnh cho pha my khch Vi t chng trnh cho pha my khch Xc nh a ch c a Server T o Socket K t n i n Server G i nh n d li u theo giao th c thi t k ng Socket Vi t 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. 14 s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("Server gui:{0}", s); } client.Disconnect(true); client.Close(); } } 2.1.4. S d ng cc lu ng nh p xu t v i Socket T Socket ta c th t o ra lu ng nh p xu t v i Socket l s d ng l p NetworkStream Property Description CanRead Is true if the NetworkStream supports reading CanSeek Is always false for NetworkStreams CanWrite Is true if the NetworkStream supports writing DataAvailable Is true if there is data available to be read V d chng trnh Client/Server s d ng NetworkStream g i v nh n d li u Chng trnh Client s d ng NetworkStream: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; 15. 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 d ng NetworkStream: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; class Program { static void Main(string[] args) { IPEndPoint iep=new IPEndPoint(IPAddress.Parse("127.0.0.1"),2009); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Bind(iep); server.Listen(10); Socket client = server.Accept(); byte[] data; NetworkStream ns = new NetworkStream(client); while (true) { data = new byte[1024]; int rec = ns.Read(data, 0, data.Length); string s = Encoding.ASCII.GetString(data, 0, rec); Console.WriteLine(s); data = new byte[1024]; s = s.ToUpper(); if (s.Equals("QUIT")) break; data = Encoding.ASCII.GetBytes(s); ns.Write(data, 0, data.Length); } 16. 16 client.Close(); server.Close(); } } Trn c s c a NetworkStream ta c th n i thm cc lu ng nh p xu t theo h ng k t nh StreamReader, StreamWriter Sau y l m t v d v chng trnh Client/Server s d ng lu ng nh p xu t, chng trnh Server chp php Client g i ln yu c u, n u yu c u l GetDate khng phn bi t ch hoa ch th ng th Server tr v cho Client ngy hi n t i, n u yu c u l GetTime khng phan bi t hoa th ng th Server tr v gi hi n t i, n u l Quit th Server ng t k t n i v i Client, khng ph i cc tr ng h p trn th thng bo khng hi u 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. 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 h ng k t n i (UDP Socket) Chng trnh pha my ch T o m t Socket Lin k t v i m t IPEndPoint c c b G i nh n d li u theo giao th c thi t k ng Socket Chng trnh pha my khch Xc nh a ch Server T o Socket G i nh n d li u theo giao th c thi t k ng Socket 2.2.1. Vi t chng trnh cho pha my ch using System; 18. 18 using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; class Program { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); server.Bind(iep); //tao ra mot Endpot tu xa de nhan du lieu ve IPEndPoint RemoteEp = new IPEndPoint(IPAddress.Any, 0); EndPoint remote=(EndPoint)RemoteEp; byte[] data = new byte[1024]; int recv = server.ReceiveFrom(data, ref remote); string s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("nhan ve tu Client:{0}", s); data = Encoding.ASCII.GetBytes("Chao client"); server.SendTo(data, remote); while (true) { data=new byte[1024]; recv = server.ReceiveFrom(data, ref remote); s = Encoding.ASCII.GetString(data, 0, recv); if (s.ToUpper().Equals("QUIT")) break; Console.WriteLine(s); data=new byte[1024]; data=Encoding.ASCII.GetBytes(s); server.SendTo(data,0,data.Length,SocketFlags.None,remote); } server.Close(); } } 2.2.2. Vi t 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. 19 data = new byte[1024]; int recv = client.ReceiveFrom(data, ref remote); s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("Nhan ve tu Server{0}",s); while (true) { s = Console.ReadLine(); data=new byte[1024]; data = Encoding.ASCII.GetBytes(s); client.SendTo(data, remote); if (s.ToUpper().Equals("QUIT")) break; data = new byte[1024]; recv = client.ReceiveFrom(data, ref remote); s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(s); } client.Close(); } } S d ng Socket khng h ng k t n i vi t chng trnh chat gia 2 my nh sau: (Sau ny chng ta c th s d ng l p UdpClient) using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; public partial class Form1 : Form { private Socket udp1; private IPEndPoint ipremote, iplocal; public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void btStart_Click(object sender, EventArgs e) { udp1 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); iplocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(txtLocalPort.Text)); udp1.Bind(iplocal); ipremote = new IPEndPoint(IPAddress.Parse(txtIp.Text), int.Parse(txtRemotePort.Text)); Thread tuyen = new Thread(new ThreadStart(NhanDL)); tuyen.Start(); 20. 20 } private void btSend_Click(object sender, EventArgs e) { byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes(txtSend.Text); udp1.SendTo(data, ipremote); } private void NhanDL() { while (true) { byte[] data = new byte[1024]; IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0); EndPoint remote = (EndPoint)ipe; int rec = udp1.ReceiveFrom(data, ref remote); string s = Encoding.ASCII.GetString(data, 0, rec); txtNoidung.Text += s + "rn"; } } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(txtSend.Text.Substring(0, txtSend.Text.IndexOf(" "))); } } 2.2.3. S d ng l p System.IO.MemoryStream t o vng m nh p xu t 2.3. S d ng cc l p h tr c xy d ng t l p Soket 21. 21 2.3.1. L p TCPClient M c ch c a l p UDPClient trn l dng cho l p trnh v i giao th c UDP, v i giao th c ny th hai bn khng c n ph i thi t l p k t n i tr c khi g i do v y m c tin c y khng cao. m b o tin c y trong cc ng d ng m ng, ng i ta cn dng m t giao th c khc, g i l giao th c c k t n i : TCP (Transport Control Protocol). Trn Internet ch y u l dng lo i giao th c ny, v d nh Telnet, HTTP, SMTP, POP3 l p trnh theo giao th c TCP, MS.NET cung c p hai l p c tn l TCPClient v TCPListener. - Cc thnh ph n c a l p TcpClient + Phng th c kh i t o: Constructor Method Name Description TcpClient () T o m t i t ng TcpClient. Cha t thng s g. TcpClient (IPEndPoint) T o m t TcpClient v g n cho n m t EndPoint c c b . (Gn a ch my c c b v s hi u c ng s d ng trao i thng tin v sau) TcpClient (RemoteHost: String, Int32) T o m t i t ng TcpClient v k t n i n m t my c a ch v s hi u c ng c truy n vo.. RemoteHost c th l a ch IP chu n ho c tn my. + M t s thu c tnh: Name Description Available Cho bi t s byte nh n v t m ng v c s n c. Client Tr v Socket ng v i TCPClient hi n hnh. Connected Tr ng thi cho bi t k t n i c n Server hay cha ? + M t s phng th c: Name Description Close Gi i phng i t ng TcpClient nhng khng ng k t n i. Connect (RemoteHost, Port) K t n i n m t my TCP khc c Tn v s hi u c ng. 22. 22 GetStream Tr v NetworkStream t gip ta g i hay nh n d li u. (Th ng lm tham s khi t o StreamReader v StreamWriter) . Khi g n vo StreamReader v StreamWriter r i th ta c th g i v nh n d li u thng qua cc phng th c Readln, writeline tng ng c a cc l p ny. Ta s d ng l p TcpClient vi t l i 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. L p TCPListener TCPListerner l m t l p cho php ng i l p trnh c th xy d ng cc ng d ng Server (V d nh SMTP Server, FTP Server, DNS Server, POP3 Server hay server t nh ngha .). ng d ng server khc v i ng d ng Client ch n lun lun th c hi n l ng nghe v ch p nh n cc k t n i n t Client. 23. 23 Cc thnh ph n c a l p TcpListener: + Phng th c kh i t o: Constructor method Name Description TcpListener (Port: Int32) T o m t TcpListener v l ng nghe t i c ng ch nh. TcpListener (IPEndPoint) T o m t TcpListener v i gi tr Endpoint truy n vo. TcpListener (IPAddress, Int32) T o m t TcpListener v l ng nghe cc k t n i n t i a ch IP v c ng ch nh. + Cc phng th c khc Name Description AcceptSocket Ch p nh n m t yu c u k t n i ang ch . AcceptTcpClient Ch p nh n m t yu c u k t n i ang ch . ( ng d ng s d ng t i l nh ny cho n khi no c m t k t n i n) Pending Cho bi t li u c k t n i no ang ch i khng ? (True = c). Start B t u l ng nghe cc yu c u k t n i. Stop D ng vi c nghe. S d ng l p TcpListener ta vi t l i 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. 24 string s = sr.ReadLine(); s=s.ToUpper(); if (s.Equals("QUIT")) break; if (s.Equals("GETDATE")) kq = DateTime.Now.ToString("dd/MM/yyyy"); else if (s.Equals("GETTIME")) kq = DateTime.Now.ToString("hh:mm:ss"); else kq = "Khong hieu lenh"; sw.WriteLine(kq); sw.Flush(); } sr.Close(); sw.Close(); client.Close(); } } 2.3.3. L p UDPClient Giao 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 s ng hay cha ? (Ni cch khc l khng cn thit lp kt ni gia hai bn khi tin h nh trao i thng tin). Giao thc n y khng tin cy bng giao thc TCP nhng tc li nhanh v d c i t. Ngo i 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. 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 d ng UdpClient vi t chng trnh Chat gi a 2 my: Do chng trnh 2 my l nh nhau ta ch c n vi t m t chng trnh copy ra s d ng. Hnh nh c a n nh sau: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; 26. 26 using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace UdpChat { public partial class Form1 : Form { public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void btSend_Click(object sender, EventArgs e) { UdpClient send = new UdpClient(); IPEndPoint iepRemote = new IPEndPoint(IPAddress.Parse(txtIp.Text), int.Parse(txtRemotePort.Text)); byte[] data = new byte[1024]; data = Encoding.UTF8.GetBytes(txtSend.Text); send.Send(data, data.Length, iepRemote); txtReceive.Text += "Sender: "+txtSend.Text + "rn"; txtSend.Clear(); if (txtSend.Text.ToUpper().Equals("QUIT")) this.Dispose(); } private void btConnect_Click(object sender, EventArgs e) { Thread tuyen = new Thread(new ThreadStart(NhanDl)); tuyen.Start(); } private void NhanDl() { UdpClient receiver = new UdpClient(int.Parse(txtLocalPort.Text)); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0); while (true) { byte[] data = new byte[1024]; data = receiver.Receive(ref iep); string s = Encoding.UTF8.GetString(data); if (s.Trim().ToUpper().Equals("QUIT")) break; txtReceive.Text += "Receiver: "+ s + "rn"; } } } } 2.4. Socket khng ng b 2.4.1. M hnh x l s ki n c a windows 27. 27 M hnh x l s ki n c a Windows c th hi n qua hnh sau: Nh v y thng qua m hnh ny ta c th y nhi m cho m t th t c no th c hi n khi s ki n s y 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 ki n Click c a button 1 chng ta thm m t x ki n khi button1 c nh n l s ki n NhanTiep. 2.4.2. S d ng Socket khng ng b l p trnh khng ng b v i Socket chng ta s d ng cc phng th c cho vi c s d ng b t ng b 28. 28 Cc phng th c cho vi c l p trnh b t ng b c chia lm 2 l i th ng b t u b ng Begin v End: Phng th c b t u b ng Begin, b t u m t ch c nng v c ng k v i phng th c AsyncCallback B t u b ng End ch ch c nng hon thnh khi AsyncCallback c g i. EndSendTo()To send data to a specific remote host BeginSendTo() EndSend()To send data from a socket BeginSend() EndReceiveFrom()To retrieve data from a specific remote host BeginReceiveFrom() EndReceive()To retrieve data from a socket BeginReceive() EndConnect()To connect to a remote host BeginConnect() EndAccept()To accept an incoming connection BeginAccept() Requests Ended BYDescription of RequestRequests Started By EndSendTo()To send data to a specific remote host BeginSendTo() EndSend()To send data from a socket BeginSend() EndReceiveFrom()To retrieve data from a specific remote host BeginReceiveFrom() EndReceive()To retrieve data from a socket BeginReceive() EndConnect()To connect to a remote host BeginConnect() EndAccept()To accept an incoming connection BeginAccept() Requests Ended BYDescription of RequestRequests Started By - ch p nh n k t n i b t ng b ta s d ng phng th c BeginAccept() v EndAccept() nh sau: Phng th c BeginAccept() v EndAccept() IAsyncResult BeginAccept(AsyncCallback callback, object state) Socket EndAccept(IAsyncResult iar); Th ng 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 th c CallAccept th ng c vi t nh sau: private static void CallAccept(IAsyncResult iar) { Socket server = (Socket)iar.AsyncState; Socket client = server.EndAccept(iar); . . . } - thi t l p k t n i theo cch b t ng b chng ta s d ng phng th c BeginConnect() v EndConnect() nh sau: Phng th c BeginConnect() v EndConnect() 29. 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 th c Connected th ng c vi t nh sau: public static void Connected(IAsyncResult iar) { Socket sock = (Socket)iar.AsyncState; try { sock.EndConnect(iar); } catch (SocketException) { Console.WriteLine("Unable to connect to host"); } } - g i d li u b t ng b chng ta lm nh sau: + Phng th c BeginSend() v EndSend() + BeginSend() IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags sockflag, AsyncCallback callback, object state) V d : sock.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendData), sock); + EndSend() int EndSend(IAsyncResult iar) Trong phng th c SendData th ng c vi t nh sau: private static void SendData(IAsyncResult iar) { Socket server = (Socket)iar.AsyncState; int sent = server.EndSend(iar); } Tng t nh giao th c h ng k t n i n u ta s d ng g i d li u theo giao th c khng h ng k t n i chng ta cng th c hi n tng t nh sau: Phng th c BeginSendTo() v EndSendTo() IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags sockflag, EndPoint ep, AsyncCallback callback, object state) V d : IPEndPoint iep = new EndPoint(IPAddress.Parse("192.168.1.6"), 9050); sock.BeginSendTo(data, 0, data.Length, SocketFlags.None, iep, new AsynCallback(SendDataTo), sock); int EndSendTo(IAsyncResult iar) - nh n d li u b t ng b ta th c hi n nh sau: + Nh n d li u v i giao th c h ng k t n i: Phng th c BeginReceive v EndReceive() 30. 30 sock.BeginReceive(data, 0, data.Length, SocketFlags.None, new AsyncCallback(ReceivedData), sock); V i 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); } + Nh n d li u b t ng b v i giao th c khng h ng k t n i. Phng th c BeginReceiveFrom() and EndReceiveFrom() sock.BeginReceive(data, 0, data.Length, SocketFlags.None, ref iep, new AsyncCallback(ReceiveData), sock); void ReceiveData(IasyncResult iar){ Socket remote = (Socket)iar.AsyncState; int recv = remote.EndReceiveFrom(iar); string stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(stringData); } 2.4.3. V d v Socket khng ng b Sau y chng ta s s d ng cc phng th c khng ng b vi t chng trnh Client/Server theo Socket b t ng b , m i khi Client g i d li u ln Server, n s in ra v g i tr l i cho Client. M hnh c a client/server s d ng cc phng th c b t ng b nh sau: 31. 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. 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. 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. 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. 35 int sent = client.EndSend(iar); client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client); } void ReceiveData(IAsyncResult iar) { Socket client = (Socket)iar.AsyncState; int recv = client.EndReceive(iar); if (recv == 0) { client.Close(); conStatus.Text = "Waiting for client..."; server.BeginAccept(new AsyncCallback(AcceptConn), server); return; } string receivedData = Encoding.ASCII.GetString(data, 0, recv); results.Items.Add(receivedData); byte[] message2 = Encoding.ASCII.GetBytes(receivedData); client.BeginSend(message2, 0, message2.Length, SocketFlags.None, new AsyncCallback(SendData), client); } public static void Main() { Application.Run(new AsyncTcpSrvr()); } } 2.4.4. S d ng cc phng th c Non-blocking l p trnh b t ng b chng ta c th s d ng cc phng th c Non bloking nh phng th c Poll() v phng th c Select: + Phng th c Poll() bool Poll(int microseconds, SelectMode mode); SelectRead: Poll() tr v true n u m t trong nh ng i u ki n sau c tho : N u phng th c Accept() thnh cng N u c d li u trn Socket N u k t n i ng SelectWrite: Poll() tr v true n u tho m t trong nh ng i u ki n sau: Phng th c Connect() thnh cng N u c d li u trn Socket g i SelectError: Poll() tr v true n u m t trong nh ng i u ki n sau c tho : N u phng th c Connect() th t b i N u c d li u ngoi bng thng chu n g i n nhng thu c tnh OutOfBandInline khng c thi t l p l true. + Phng th c Select(): 36. 36 Socket.Select(IList checkRead, IList checkWrite, IList checkError, int microseconds) checkRead monitors the specified sockets for the ability to read data from the socket. checkWrite monitors the specified sockets for the ability to write data to the socket. checkError monitors the specified sockets for error conditions. V d ng d ng Server s d ng phng th c Poll() using System; using System.Net; using System.Net.Sockets; using System.Text; class TcpPollSrvr { public static void Main() { int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waiting for a client..."); bool result; int i = 0; while (true) { i++; Console.WriteLine("polling for accept#{0}...", i); result = newsock.Poll(1000000, SelectMode.SelectRead); if (result) { break; } } Socket client = newsock.Accept(); IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); client.Send(data, data.Length, SocketFlags.None); 37. 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 vi t m t chng trnh Server s d ng phng th c Select() ch p nh n 2 k t n i n t client v x l t ng k t n i. 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. 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. 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 d ng Thread trong cc ng d ng m ng 40. 40 M t s khi ni m - a nhi m (Multitasking): L kh nng h iu hnh lm nhi u cng vi c t i m t th i i m - Ti n trnh (Process): Khi ch y m t ng d ng, h i u hnh s c p pht ring cho ng d ng b nh v cc ti nguyn khc. B nh v ti nguyn v t l ring bi t ny c g i l m t ti n trnh. Cc ti nguyn v b nh c a m t ti n trnh th ch ti n trnh c php truy c p. - Tuy n (Thread): Trong h th ng, m t ti n trnh c th c m t ho c nhi u chu i th c hi n tch bi t nhau v c th ch y ng th i. M i chu i th c hi n ny c g i l m t tuy n (Thread). Trong m t ng d ng, Thread kh i t o u tin g i l Thread s c p hay Thread chnh. 2.5.1. S d ng Thread trong chng trnh .Net s d ng Thread trong .Net ta s d ng NameSpace System.Threading - M t s phng th c th ng dng Public Method Name M t Abort() K t thc Thread Join() Bu c chng trnh ph i ch cho thread k t thc (Block) th m i th c hi n ti p (cc cu l nh ng sau Join). Resume() Ti p t c ch y thread b t m ngng - suspended. Sleep() Static method : T m d ng thread trong m t kho ng th i gian. Start() B t u ch y (kh i ng) m t thread. Sau khi g i phng th c ny, tr ng thi c a thread chuy n t tr ng thi hi n hnh sang Running. Suspend() T m ngng (ngh ) thread. (Phng th c ny b lo i kh i phin b n VS.NET 2005) - M t s thu c tnh th ng dng: Public Property Name M t CurrentThread This static property: Tr v thread hi n hnh ang ch y. IsAlive Tr v gi tr cho bi t tr ng thi th c thi c a thread hi n hnh. IsBackground Sets or gets gi tr cho bi t l thread l background hay foreground thread. IsThreadPoolThread Gets a value indicating whether a thread is part of a thread pool. Priority Sets or gets gi tr ch nh u tin (dnh nhi u hay t CPU cho thread). Cao nh t l 4, th p nh t l 0. 41. 41 Public Property Name M t ThreadState L y v tr ng thi c a thread (ang d ng, hay ang ch y) - T o m t tuy n trong C# Thread newThread=newThread(new ThreadStart(newMethod)); . } void newMethod() { . . . } 2.5.2. S d ng Thread trong cc chng trnh Server - a tuyn hay c ng d ng trong cc chng trnh Server, cc chng trnh i h i t i m t th i i m ch p nh n nhi u k t n i n t cc Client. - cc chng trnh Server c th x l nhi u Client t i m t th i i m ta c m hnh ng d ng a tuy n nh sau: Sau y chng ta vi t l i chng trnh DateTimeServer c s d ng Thread nh sau: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; class Program { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2009); TcpListener server = new TcpListener(iep); server.Start(); while (true) { 42. 42 //chap nhan ket noi TcpClient client= server.AcceptTcpClient(); //Tao ra tuyen moi de xu ly moi Client new ClientThread(client); } server.Stop(); } } class ClientThread { private Thread tuyen; private TcpClient client; public ClientThread(TcpClient client) { this.client = client; tuyen = new Thread(new ThreadStart(GuiNhanDL)); tuyen.Start(); } private void GuiNhanDL() { StreamReader sr = new StreamReader(client.GetStream()); StreamWriter sw= new StreamWriter(client.GetStream()); string kq=""; while(true) { string s=sr.ReadLine(); s=s.ToUpper(); if(s.Equals("QUIT")) break; if(s.Equals("GETDATE")) kq=DateTime.Now.ToString("dd/MM/yyyy"); else if(s.Equals("GETTIME")) kq=DateTime.Now.ToString("hh:mm:ss"); else kq="Khong hieu lenh"; sw.WriteLine(kq); sw.Flush(); } client.Close(); } } 2.5.3. S d ng Thread g i/nh n d li u ng d ng a tuy n trong vi c g i nh n d li u chng ta vi t chng trnh Chat theo giao th c TCP nh sau: 43. 43 ng d ng m hnh x l s ki n c a Windows v a tuy n v Socket khng ng b ta ch c n vi t m t chng trnh sau d ch ra, ta ch y ng d ng nh n Listen n s l ng nghe trong vai tr Server cn khi ta ch y v nh n Connect n s ng vai tr Client v k t n i t i Server. Vn b n chng trnh nh sau: using System; using System.Drawing; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; 44. 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. 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. 46 string stringData; while (true) { recv = client.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); if (stringData == "bye") break; results.Items.Add(stringData); } stringData = "bye"; byte[] message = Encoding.ASCII.GetBytes(stringData); client.Send(message); client.Close(); results.Items.Add("Connection stopped"); return; } public static void Main() { Application.Run(new TcpChat()); } } 2.5.4. S d ng ThreadPool trong 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. 47 public static void Main() { ThreadPoolSample tps = new ThreadPoolSample(); } public ThreadPoolSample() { int i; ThreadPool.QueueUserWorkItem(new WaitCallback(Counter)); ThreadPool.QueueUserWorkItem(new WaitCallback(Counter2)); for(i = 0; i < 10; i++) { Console.WriteLine("main: {0}", i); Thread.Sleep(1000); } } void Counter(object state) { int i; for (i = 0; i < 10; i++) { Console.WriteLine(" thread: {0}", i); Thread.Sleep(2000); } } void Counter2(object state) { int i; for (i = 0; i < 10; i++) { Console.WriteLine(" thread2: {0}", i); Thread.Sleep(3000); } } } 2.5.5. S d ng ThreadPool trong 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. 48 } } class ConnectionThread { public TcpListener threadListener; private static int connections = 0; public void HandleConnection(object state) { int recv; byte[] data = new byte[1024]; TcpClient client = threadListener.AcceptTcpClient(); NetworkStream ns = client.GetStream(); connections++; Console.WriteLine("New client accepted: {0} active connections", connections); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); ns.Write(data, 0, data.Length); while(true) { data = new byte[1024]; recv = ns.Read(data, 0, data.Length); if (recv == 0) break; ns.Write(data, 0, recv); } ns.Close(); client.Close(); connections; Console.WriteLine("Client disconnected: {0} active connections", connections); } } 2.6. K thu t IP Multicasting 2.6.1. Broadcasting l g? Broadcast, ti ng Vi t g i l qu ng b. Trong h th ng m ng h u tuy n, qu ng b l thu t ng dng ch vi c g i m t gi thng tin n t t cc nt m ng trong m ng. th c hi n hnh th c qu ng b, a ch n c a gi tin s l a ch qu ng b. C hai lo i l: Local Broadcast v Global Broadcast 2.6.2. S d ng Broadcasting g i d li u n nhi u my trong m ng c c b G i gi d li u Broadcast using System; using System.Net; using System.Net.Sockets; using System.Text; class BadBroadcast { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9050); byte[] data = Encoding.ASCII.GetBytes("This is a test message"); sock.SendTo(data, iep); sock.Close(); } 49. 49 } Chng ta ph i thi t l p nh sau: class Broadcst { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050); IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050); string hostname = Dns.GetHostName(); byte[] data = Encoding.ASCII.GetBytes(hostname); sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); sock.SendTo(data, iep1); sock.SendTo(data, iep2); sock.Close(); } } Nh n gi d li u Broadcast class RecvBroadcst { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); sock.Bind(iep); EndPoint ep = (EndPoint)iep; Console.WriteLine("Ready to receive"); byte[] data = new byte[1024]; int recv = sock.ReceiveFrom(data, ref ep); string stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString()); data = new byte[1024]; recv = sock.ReceiveFrom(data, ref ep); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString()); sock.Close(); } } 2.6.3. Multicasting l g? M t a ch multicast cho php thi t b g i d li u t i m t t p xc nh tr c cc host, c bi t n nh cc nhm multicast, trong cc m ng con khc nhau. M t s a ch Multicast a ch multicast Ch c nng 224.0.0.0 a ch c s 224.0.0.1 T t c cc h th ng trn m ng con ny 224.0.0.2 T t c cc Router trn m ng con ny 50. 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 thu t Multicast c s d ng + Peer to Peer + Central Server 2.6.4. Socket Multicasting trong .Net S d ng phng th c SetSocketOption() 51. 51 Socket option c th c s d ng Thm m t Socket vo nhm Multicast Lo i m t Socket kh i nhm Multicast SetSocketOption(SocketOptionLevel,SocketOptionName, optionValue) SocketOptionName AddMembership DropMembership S d ng phng th c SetSocketOption() Socket option c th c s d ng optionValue l m t i t ng c a l p MulticastOption MulticastOption(IPAddress) MulticastOption(IPAddress,IPAddress) V d thm m t Socket vo nhm Multicast 224.100.0.1 sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.100.0.1")); G i d li u Multicast class MultiSend{ public static void Main() { Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050); byte[] data = Encoding.ASCII.GetBytes("This is a test message"); server.SendTo(data, iep); server.Close(); } } Nh n d li u Multicast class MultiRecv{ public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); Console.WriteLine("Ready to receive"); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); EndPoint ep = (EndPoint)iep; sock.Bind(iep); sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.100.0.1"))); byte[] data = new byte[1024]; int recv = sock.ReceiveFrom(data, ref ep); string stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString()); sock.Close(); } } 52. 52 G i d li u Multicast v i TTL class NewMultiSend{ public static void Main() { Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051); IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050); server.Bind(iep); byte[] data = Encoding.ASCII.GetBytes("This is a test message"); server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.100.0.1"))); server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 50); server.SendTo(data, iep2); server.Close(); } } Multicast v i l p UdpClient JoinMulticastGroup() DropMulticastGroup() JoinMulticastGroup() l phng th c overload JoinMulticastGroup(IPAddress) JoinMulticastGroup(IPAddress, int) class UdpClientMultiSend{ public static void Main() { UdpClient sock = new UdpClient(); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050); byte[] data = Encoding.ASCII.GetBytes("This is a test message"); sock.Send(data, data.Length, iep); sock.Close(); } } class UdpClientMultiRecv { public static void Main() { UdpClient sock = new UdpClient(9050); Console.WriteLine("Ready to receive"); sock.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0); byte[] data = sock.Receive(ref iep); string stringData = Encoding.ASCII.GetString(data, 0, data.Length); Console.WriteLine("received: {0} from: {1}", stringData, iep.ToString()); sock.Close(); } } 53. 53 2.7 Bi t p p d ng class MulticastChat : Form{ TextBox newText; ListBox results; Socket sock; Thread receiver; IPEndPoint multiep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050); public MulticastChat() { Text = "Multicast Chat Program"; Size = new Size(400, 380); Label label1 = new Label(); label1.Parent = this; label1.Text = "Enter text string:"; label1.AutoSize = true; label1.Location = new Point(10, 30); newText = new TextBox(); newText.Parent = this; newText.Size = new Size(200, 2 * Font.Height); newText.Location = new Point(10, 55); results = new ListBox(); results.Parent = this; results.Location = new Point(10, 85); results.Size = new Size(360, 18 * Font.Height); Button sendit = new Button(); sendit.Parent = this; sendit.Text = "Send"; sendit.Location = new Point(220, 52); sendit.Size = new Size(5 * Font.Height, 2 * Font.Height); sendit.Click += new EventHandler(ButtonSendOnClick); Button closeit = new Button(); closeit.Parent = this; closeit.Text = "Close"; closeit.Location = new Point(290, 52); closeit.Size = new Size(5 * Font.Height, 2 * Font.Height); closeit.Click += new EventHandler(ButtonCloseOnClick); sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); sock.Bind(iep); sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, 54. 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. 55 CHNG 3: XY D NG NG D NG M NG 3.1. Giao th c ICMP Gi i thi u giao th c ICMP (Internetwork Control Message Protocol) - Giao th c ICMP ho t ng trn layer 2 - Internetwork trong m hnh TCP/IP ho c layer 3 - Network trong m hnh OSI Cho php ki m tra v xc nh l i c a Layer 3 Internetwork trong m hnh TCP/IP b ng cch nh ngha ra cc lo i thng i p c th s d ng xc nh xem m ng hi n t i c th truy n c gi tin hay khng. Trong th c t , ICMP c n cc thnh ph n c a m i gi tin IP c th ho t ng c. C u trc c a gi tin IP v ICMP + Type: c th l m t query hay m t l i + Code: Xc nh y l lo i query hay thng i p l i + Checksum: Ki m tra v s a l i cho d li u ICMP + Message: Tu thu c vo Type v Code 3.1.1. S d ng Raw Socket Gi tin ICMP khng s d ng TCP ho c UDP nn chng ta khng th s d ng cc l p c h tr nh TcpClient hay UdpClient m ph i s d ng m t Raw Socket Mu n t o Raw Socket khi t o ra Socket b n s d ng SocketType.Raw, giao th c ICMP T o Raw Socket nh sau Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); Raw Socket Format Value Description Ggp Gateway-to-Gateway Protocol Icmp Internet Control Message Protocol 56. 56 Idp IDP Protocol Igmp Internet Group Management Protocol IP A raw IP packet Ipx Novell IPX Protocol ND Net Disk Protocol Pup Xerox PARC Universal Protocol (PUP) Raw A raw IP packet Spx Novell SPX Protocol SpxII Novell SPX Version 2 Protocol Unknown An unknown protocol Unspecified An unspecified protocol G i gi d li u Raw ICMP l giao th c khng h ng k t n i S d ng phng th c SendTo() c a l p Socket g i C ng trong giao th c ICMP khng quan tr ng IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 0); sock.SendTo(packet, iep); Nh n gi d li u Raw S d ng phng th c ReceiveForm c a l p Socket D li u nh n v l m t gi tin IP chng ta ph i tch ra l y gi tin ICMP Raw Socket khng t ng nh d ng gi tin ICMP cho chng ta. Chng ta ph i 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 l p v phng th c kh i t o m c nh class ICMP { public byte Type; public byte Code; public UInt16 Checksum; public int Messagesize; public byte[] Message = new byte[1024]; public ICMP() { } } T o ra gi tin ICMP ICMP packet = new ICMP(); 57. 57 packet.Type = 0x08; packet.Code = 0x00; packet.Checksum = 0; public ICMP(byte[] data, int size) { Type = data[20]; Code = data[21]; Checksum = BitConverter.ToUInt16(data, 22); MessageSize = size - 24; Buffer.BlockCopy(data, 24, Message, 0, MessageSize); } public byte[] getBytes() { byte[] data = new byte[MessageSize + 9]; Buffer.BlockCopy(BitConverter.GetBytes(Type), 0, data, 0, 1); Buffer.BlockCopy(BitConverter.GetBytes(Code), 0, data, 1, 1); Buffer.BlockCopy(BitConverter.GetBytes(Checksum), 0, data, 2, 2); Buffer.BlockCopy(Message, 0, data, 4, MessageSize); return data; } public UInt16 getChecksum() { UInt32 chcksm = 0; byte[] data = getBytes(); int packetsize = MessageSize + 8; int index = 0; while (index < packetsize) { chcksm += Convert.ToUInt32(BitConverter.ToUInt16(data, index)); index += 2; } chcksm = (chcksm >> 16) + (chcksm & 0xffff); chcksm += (chcksm >> 16); return (UInt16)(~chcksm); } 3.1.2. S d ng giao th c ICMP v Raw Socket xy d ng chng trnh Ping 58. 58 class Program { static void Main(string[] args) { byte[] data = new byte[1024]; int recv; Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse(argv[0]), 0); EndPoint ep = (EndPoint)iep; ICMP packet = new ICMP(); packet.Type = 0x08; packet.Code = 0x00; packet.Checksum = 0; Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 0, 2); Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 2, 2); data = Encoding.ASCII.GetBytes("test packet"); Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length); packet.MessageSize = data.Length + 4; int packetsize = packet.MessageSize + 4; UInt16 chcksum = packet.getChecksum(); packet.Checksum = chcksum; host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000); host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep); try { data = new byte[1024]; recv = host.ReceiveFrom(data, ref ep); } catch (SocketException) { Console.WriteLine("No response from remote host"); return; } ICMP response = new ICMP(data, recv); Console.WriteLine("response from: {0}", ep.ToString()); Console.WriteLine(" Type {0}", response.Type); Console.WriteLine(" Code: {0}", response.Code); int Identifier = BitConverter.ToInt16(response.Message, 0); 59. 59 int Sequence = BitConverter.ToInt16(response.Message, 2); Console.WriteLine(" Identifier: {0}", Identifier); Console.WriteLine(" Sequence: {0}", Sequence); string stringData = Encoding.ASCII.GetString(response.Message, 4, response.MessageSize - 4); Console.WriteLine(" data: {0}", stringData); host.Close(); } } 3.1.3. S d ng giao th c ICMP v Raw Socket xy d ng 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. 60 } badcount = 0; } catch (SocketException) { Console.WriteLine("hop {0}: No response from remote host", i); badcount++; if (badcount == 5) { Console.WriteLine("Unable to contact remote host"); break; } } } host.Close(); } } 3.2. Giao th c SMTP, POP3 3.2.1. C b n v h th ng Mail v giao th c SMTP, POP3 61. 61 * Giao th c SMTP M t s l nh c b n c a giao th c SMTP: L nh M t HELO Hello. S d ng xc nh ng i g i i n. L nh ny ny i km v i tn c a host g i i n. Trong ESTMP (extended protocol), th l nh ny s l EHLO. MAIL Kh i t o m t giao d ch g i th. N k t h p "from" xc nh ng i g i th. RCPT Xc nh ng i nh n th. DATA Thng bo b t u n i dung th c s c a b c i n (ph n thn c a th). D li u c m thnh d ng m 128-bit ASCII v n c k t thc v i m t dng n ch a d u ch m (.). RSET Hu b giao d ch th VRFY S d ng xc th c ng i nh n th. NOOP N l l nh "no operation" xc nh khng th c hi n hnh ng g QUIT Thot kh i ti n trnh k t thc SEND Cho host nh n bi t r ng th cn ph i g i n u cu i khc. M t s l nh khng yu c u ph i c c xc nh b ng RFC 821 SOMLSend or mail. Bo v i host nh n th r ng th ph i g i n u cu i khc ho c h p th. SAML Send and mail. Ni v i host nh n r ng b c i n ph i g i t i ng i dng u cu i v h p th. EXPN S d ng m r ng cho m t mailing list. HELP Yu c u thng tin gip t u nh n th. TURN Yu c u host nh n gi vai tr l host g i th. - M tr ng thi c a SMTP Khi m t MTA g i m t l nh SMTP t i MTA nh n th MTA nh n s tr l i v i m t m tr ng thi cho ng i g i bi t ang c vi c g x y ra u nh n. V d i y l b ng m tr ng thi c a SMTP theo tiu chu n RFC 821. M c c a tr ng thi c 62. 62 xc nh b i s u tin c a m (5xx l l i n ng, 4xx l l i t m th i, 1xx3xx l ho t ng bnh th ng). - M t s m tr ng thi c a SMTP 211 Tnh tr ng h th ng, hay reply gip h th ng 214 Thng i p gip . 220 d ch v s n sng 221 d ch v ng knh giao chuy n 250 Hnh ng mail yu c u OK, hon thnh 251 User khng c c b ; s h ng n 354 Kh i ng vi c nh p mail; k t thc v i . 421 d ch v khng s d ng c, ng knh giao chuy n 450 Khng l y hnh ng mail yu c u; mailbox khng hi u l c 451 Khng nh n hnh ng c yu c u; lu tr c a h th ng khng . 500 L i c php; khng ch p nh n l nh 501 L i c php trong tham s hay i s 502 L nh khng c cung c p 503 Dng l nh sai 504 Tham s c a dng l nh khng c cung c p 550 Khng nh n hnh ng c yu c u ; mailbox khng hi u l c [nh mailbox khng tm th y hay khng truy c p c] 551 User khng c c b ; vui lng th 552 B qua hnh ng m mail yu c u, v t qu ch nh lu tr 554 Khng nh n hnh ng c yu c u; tn mailbox khng c ch p nh n. [nh sai c php mailbox] giao chuy n sai. - nh d ng c a m t b c th thng th ng khng c ph n nh km nh sau: * Giao th c POP3 Giao th c dng l y th, POP3 Server l ng nghe trn c ng 110, m t trong RFC 1939 63. 63 - M t s l nh c a POP3 USER Xc nh username PASS Xc nh password STAT Yu c u v tr ng thi c a h p th nh s l ng th v l n c a th LIST Hi n danh sch c a th RETR Nh n th DELE Xo m t b c th xc nh NOOPKhng lm g c RSET Khi ph c l i nh th xo (rollback) QUIT Th c hi n vi c thay i v thot ra 3.2.2. Ci t SMTP, POP3 Client/Server Vi t chng trnh g i Mail n gi n theo giao th c SMTP using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; class Program { static void Main(string[] args) { string nguoigui, nguoinhan, tieude,body; string diachimaychu; int portmaychu; Console.Write("Nhap di chu SMTP Server:"); diachimaychu = Console.ReadLine(); Console.Write("Nhap cong cua may chu:"); portmaychu = int.Parse(Console.ReadLine()); Console.Write("Nhap dia chi nguoi gui:"); nguoigui = Console.ReadLine(); Console.Write("Nhap dia chi nguoi nhan:"); nguoinhan = Console.ReadLine(); Console.Write("Nhap tieu de buc thu:"); tieude = Console.ReadLine(); Console.Write("Nhap noi dung buc thu:"); body= Console.ReadLine(); //Tao Endpoit cua may chu IPEndPoint iep = new IPEndPoint(IPAddress.Parse(diachimaychu), portmaychu); TcpClient client = new TcpClient(); client.Connect(iep); string Data = "Helo"; StreamReader sr = new StreamReader(client.GetStream()); StreamWriter sw = new StreamWriter(client.GetStream()); sw.WriteLine(Data); sw.Flush(); //Doc thong bao tu Server gui ve va xu ly neu can thiet Console.WriteLine(sr.ReadLine()); 64. 64 //Gui dia chi nguyoi gui Data = "MAIL FROM: "; 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: "; sw.WriteLine(Data); sw.Flush(); //Doc thong bao tu Server gui ve va xu ly neu can thiet Console.WriteLine(sr.ReadLine()); //Bat dau gui noi dung buc thu Data = "Data"; sw.WriteLine(Data); sw.Flush(); //Doc thong bao tu Server gui ve va xu ly neu can thiet Console.WriteLine(sr.ReadLine()); //Gui noi dung buc thu Data = "SUBJECT:" + tieude + "rn" + body + "rn" + "." + "rn"; sw.WriteLine(Data); sw.Flush(); //Doc thong bao tu Server gui ve va xu ly neu can thiet Console.WriteLine(sr.ReadLine()); //Ngat ket noi Data = "QUIT"; sw.WriteLine(Data); sw.Flush(); //Doc thong bao tu Server gui ve va xu ly neu can thiet Console.WriteLine(sr.ReadLine()); sr.Close(); sw.Close(); client.Close(); Console.ReadLine(); } } 65. 65 Vi t chng trnh l y th n gi n theo giao th c POP3 using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Threading; using System.IO; using System.Net; using System.Net.Sockets; namespace MyPop3 { public partial class Form1 : Form { TcpClient popclient; StreamReader sr; StreamWriter sw; public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; 66. 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. 67 txtFrom.Text = s.Substring(5, s.Length - 5); if (s.ToUpper().StartsWith("TO")) txtTo.Text = s.Substring(3, s.Length - 3); if (s.ToUpper().StartsWith("SUBJECT")) txtSubject.Text = s.Substring(8, s.Length - 8); } //Lay phan body textBox4.Clear(); //MessageBox.Show("Lay body"); while (!sr.EndOfStream) { s = sr.ReadLine().Trim(); if (s.Equals(".")) break; textBox4.Text += s + "rn"; } //MessageBox.Show("Het noi dung buc thu"); } } } 3.3. Giao th c HTTP 3.3.1. C b n v giao th c HTTP HTTP (Hypertext Transfer Protocol) giao th c truy n siu vn b n. HTTP l giao th c t ng ng d ng cho Web. N ho t ng theo m hnh client/server. - Client: browser yu c u, nh n, hi n th cc i t ng Web. - Server: Web server g i cc i t ng Hai phin b n c a giao th c HTTP hi n c ph bi n l HTTP1.0 c c t trong RFC 1945 v HTTP1.1 c c t trong RFC 2068. HTTP l giao th c khng tr ng thi server khng lu l i cc yu c u c a client. HTTP s d ng giao th c TCP c a t ng giao v n. Cc b c ti n hnh t khi client k t n i t i server sau g i v nh n k t qu t server g i v nh sau: 68. 68 + client kh i t o k t n i TCP (t o socket) v i server, qua c ng 80 + server ch p nh n k t n i TCP t client + Cc thng i p HTTP (thng i p t ng ng d ng) c trao i gi a browser (HTTP client) v Web server (HTTP server) + ng k t n i TCP. Chng ta xem m t v d v qu trnh trao i gi a browser v Web server nh sau: C hai ki u thng i p HTTP l yu c u (Request) v tr l i (Response). Cc thng i p c nh d ng ki u m ASCII. nh d ng thng i p yu c u HTTP 5. HTTP client nh n thng i p tr l i bao g m t p html, hi n th html.Phn tch t p html file, tm 10 jpeg i t ng c tham chi u 6. Cc b c t 1 n 5 c l p l i cho t ng i t ng trong 10 i t ng jpeg 4. HTTP server ng k t n i TCP. time User nh p URL www.someSchool.edu/someDepartment/home.index 1a. HTTP client kh i t o k t n i TCP t i HTTP server (ti n trnh)t i a ch www.someSchool.edu. C ng m c nh l 80. 2. HTTP client g i thng i p yu c u HTTP (bao g m URL) vo trong TCP connection socket 1b. HTTP server i ch www.someSchool.edu i k t n i TCP c ng 80, ch p nh n k t n i, thng bo l i cho client. 3. HTTP server nh n thng i p yu c u,l y cc i t ng c yu c u g i vo trong thng i p tr l i, (someDepartment/home.index) g i thng i p vo socket (bao g m text, tham chi u t i 10 nh d ng jpeg) 69. 69 nh d ng thng i p tr l i HTTP HTTP/1.0 200 OK Date: Thu, 06 Aug 1998 12:00:15 GMT Server: Apache/1.3.0 (Unix) Last-Modified: Mon, 22 Jun 1998 ... Content-Length: 6821 Content-Type: text/html data data data data data ... Dng tr ng thi (m tr ng thi) Nh ng dng header d li u,e.g., t p html c yu c u GET /somedir/page.html HTTP/1.0 User-agent: Mozilla/4.0 Accept: text/html, image/gif,image/jpeg Accept-language:fr (CR,LF) Nh ng dng header CR,LF,k hi u k t thc thng i p Dng yu c u (l nh GET, POST, HEAD) 70. 70 Qu trnh trao i gi a Browser v Web Server c th c minh h a nh hnh sau: M tr ng thi trong thng i p HTTP Response: c ghi dng u tin trong thng i p response t server v client. M t s m th ng g p: 200 OK Yu c u thnh cng,cc i t ng c yu c u ph n sau thng i p. 301 Moved Permanently i t ng c yu c u c chuy n v a ch m i c a i t ng c t trong tr ng Location: 400 Bad Request Server khng hi u c thng i p yu c u 404 Not Found Ti li u c yu c u khng c trong server 505 HTTP Version Not Supported Server khng h tr version c a giao th c HTTP. - ki m tra cc l nh c a HTTP bn pha Client chng ta c th th c hi n nh sau: + Telnet t i Web server 71. 71 + L nh GET trong thng i p HTTP + Xem thng i p response c g i v t Server - G cc l nh khc ki m 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. // } // G i yu c u v nh n v ph n h i t web server void BtGoClick(object sender, EventArgs e){ //Thm ti n t http:// n u 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{ T o k t n i TCP c ng 80 (c ng m c nh cho HTTP server) at www.eurecom.fr. telnet www.eurecom.fr 80 GET /~ross/index.html HTTP/1.0 G i thng i p yu c u l y t p Index.html trong th m c ~ross v client 72. 72 rtfBody.Text = "Khng th k t n i n server"; return; } StreamWriter OutStream = new StreamWriter(client.GetStream()); StreamReader InpStream = new StreamReader(client.GetStream()); // G i i yu c u b ng phng th c GET OutStream.WriteLine("GET " + txtAddress.Text + " HTTP/1.0"); OutStream.WriteLine("Content-Type:text/html"); OutStream.WriteLine("Content-Language:en"); OutStream.WriteLine(); OutStream.Flush(); //L y ph n Header rtfHeader.Text = ""; string s; while (null != (s = InpStream.ReadLine())){ if (s.Equals("")) break; rtfHeader.Text += s; } //L y ph n Body rtfBody.Text = ""; int c; while (true){ c = InpStream.Read(); if (c == -1) break; rtfBody.Text += (char)c; } client.Close(); } // Khi g Enter th g i i yu c u void TxtAddressKeyPress(object sender, KeyPressEventArgs e){ if ((int)e.KeyChar == 13) btGo.PerformClick(); } // L y v tn my trong URL internal string GetHost(string url){ url = url.ToLower(); Uri tmp = new Uri(url); return tmp.Host; } // L y v s hi u c ng trong URL internal int GetPort(string url){ Uri tmp = new Uri(url); return tmp.Port; } } } b. Chng trnh HTTP Server using System; using System.IO; 73. 73 using System.Net; using System.Net.Sockets; public class SimpleWebServer { public void StartListening(int port) { IPEndPoint LocalEndPoint = new IPEndPoint(IPAddress.