Giáo trình Mạng máy tính

pdf 118 trang vanle 3430
Bạn đang xem 20 trang mẫu của tài liệu "Giáo trình Mạng máy tính", để tải tài liệu gốc về máy bạn click vào nút DOWNLOAD ở trên

Tài liệu đính kèm:

  • pdfgiao_trinh_mang_may_tinh.pdf

Nội dung text: Giáo trình Mạng máy tính

  1. Giáo trình Mạng máy tính
  2. Simpo CHƯƠNG1:CÁCKINTHCCƠBNVMNGMÁYTÍNH PDF Merge and Split Unregistered Version - 3 1.1.Môhìnhthamkho7tngOSI 3 1.2.HgiaothcTCP/IP 5 1.3.SosánhgiahaigiaothcTCPvàUDP 6 1.4.Cnggiaothc 7 1.5.ðachIP,cácñachIPdànhriêng 7 1.6.ðachtênmin:loiA,loiMX 8 1.7.Mtsgiaothctngngdng:HTTP,SMTP,POP3,FTP 8 CHƯƠNG2:LPTRÌNHMNGTRONG.NETFRAMEWORK 9 2.1.Sockethưngktni(TCPSocket) 9 2.1.1.GiithiuvNameSpaceSystem.NetvàSystem.Net.Sockets 10 2.1.2.Vitchươngtrìnhchophíamáych 11 2.1.3.Vitchươngtrìnhchophíamáykhách 13 2.1.4.SdngcáclungnhpxutviSocket 14 2.2.Socketkhônghưngktni(UDPSocket) 17 2.2.1.Vitchươngtrìnhchophíamáych 17 2.2.2.Vitchươngtrìnhchophíamáykhách 18 2.2.3.SdnglpSystem.IO.MemoryStreamñtovùngñmnhpxut 20 2.3.SdngcáclphtrñưcxâydngtlpSoket 20 2.3.1.LpTCPClient 21 2.3.2.LpTCPListener 22 2.3.3.LpUDPClient 24 2.4.Socketkhôngñngb 26 2.4.1.Môhìnhxlýskincawindows 26 2.4.2.SdngSocketkhôngñngb 27 2.4.3.VídvSocketkhôngñngb 28 2.4.4.SdngcácphươngthcNonblocking 35 2.5.SdngThreadtrongcácngdngmng 39 2.5.1.SdngThreadtrongchươngtrình.Net 40 2.5.2.SdngThreadtrongcácchươngtrìnhServer 41 2.5.3.SdngThreadñgi/nhndliu 41 2.5.4.SdngThreadPooltrongcácchươngtrình.Net 43 2.5.5.SdngThreadPooltrongcácchươngtrìnhServer 47 2.6.KthutIPMulticasting 48 2.6.1.Broadcastinglàgì? 48 2.6.2.SdngBroadcastingñgidliuñnnhiumáytrongmngccb 48 2.6.3.Multicastinglàgì? 49 2.6.4.SocketMulticastingtrong.Net 50 2.7Bàitpápdng 53 CHƯƠNG3:XÂYDNGNGDNGMNG 55 3.1.GiaothcICMP 55 3.1.1.SdngRawSocket 55 3.1.2.SdnggiaothcICMPvàRawSocketñxâydngchươngtrìnhPing 57 3.1.3.SdnggiaothcICMPvàRawSocketñxâydngchươngtrìnhTraceRoute .58 3.2.GiaothcSMTP,POP3 60 3.2.1.CơbnvhthngMailvàgiaothcSMTP,POP3 60 3.2.2.CàiñtSMTP,POP3Client/Server 60 3.3.GiaothcHTTP 67 3.3.1.CơbnvgiaothcHTTP 67 3.3.2.CàiñtHTTPClient/Server 68 3.4.GiaothcFTP 74 3.4.1.CơbnvgiaothcFTP 74 3.4.2.CàiñtFTPClient/Server 84 1
  3. Simpo PDF3.5.DNS(DomainNameServer) Merge and Split Unregistered Version - 88 3.5.1.Vnñphângiitênmin 88 3.5.2.TrinkhaiDNSMX(MailExchange) 89 3.6Tholunvcácngdngkhácthưnggp 93 3.7Bàitpápdng 93 CHƯƠNG4:XÂYDNGNGDNGNHIULP 94 4.1.Môhình2lp(twotier),3lp(threetier)vànlp. 94 4.2.Remoting 98 4.2.1.GiithiuvRemoting 102 4.2.2.Khaibáo,càiñtvàñăngkýgiaodintxa 102 4.2.3.Triugiphươngthctxa 107 4.3.WebSerive 107 4.3.1.GiithiuvWebSerives 107 4.3.2.GiaothcSOAP 109 4.3.3.XâydngWebServices 112 4.3.4.TriugiWebServicestngdng.NET,Javavàcácngônngkhác 114 4.4Tholunvcácngdngphântán 116 4.5.Bàitpápdng 116 2
  4. Simpo PDF MergeCHƯƠNG1:CÁCKINTHCCƠBNVMNGMÁYTÍNH and Split Unregistered Version - 1.1.Môhìnhthamkho7tngOSI MôhìnhktnihthngmñưcTchcquctvtiêuchunhoáISO (InternationalOrganizaitonforStandardization)ñưaranhmcungcpmtmôhình chunchocácnhàsnxutvàcungcpsnphmvinthôngápdngtheoñphát trincácsnphmvinthông.Ýtưngmôhìnhhoáñưctoracònnhmhtrcho vicktnigiacáchthngvàmodunhoácácthànhphnphcvmngvinthông. a.ChcnăngcamôhìnhOSI: Cungcpkinthcvhotñngcaktniliênmng ðưaratrìnhtcôngvicñthitlpvàthchinmtgiaothcchoktnicácthit btrênmng. MôhìnhOSIcòncómtsthunlisau: Chianhcáchotñngphctpcamngthànhcácphncôngvicñơngin. Chophépcácnhàthitkcókhnăngpháttrintrêntngmodunchcnăng. Cungcpcáckhnăngñnhnghĩacácchungiaotipcótínhtươngthíchcao “plugandplay”vàtíchhpnhiunhàcungcpsnphm. b.CutrúcmôhìnhOSI: MôhìnhOSIgm7lp(level),milpthchincácchcnăngriêngchohotñng ktnimng. Hình11MôtbylpOSI.4lpñuñnhnghĩacáchthcchoñucuithitlpkt nivinhauñtraoñidliu.3lptrêndùngñpháttrincácngdngññu cuiktnivinhauvàngưidùng. Aplication Application Presentation (UpperLayer) Session TransportLayer NetworkLayer DataLowerLayer DataLink Physical Cáclptrên 3lptrêncùngcamôhìnhOSIthưngñưcgilàcáclpngdng(Application layers)haycòngilàcáclpcao.Cáclpnàythưngliênquantigiaotipvi ngưidùng,ñnhdngcadliuvàphươngthctruynhpcácngdngñó. Hình12 Môtcáclptrênvàcungcpthôngtinvicácchcnăngcanóquaví d: Lp ng dng: chc năng giao Telnet,HTTP 3
  5. Simpo PDF Merge and Split Unregistered Version - Application tip gia ngưi s dng và các chươngtrìnhngdng Lp trình bày: cách thc chun ASSCII hoádliuvàtrìnhbàysliu Presentation EBCDIC Cóchcnăngñcbitlàmãhoá JPEC dliungưisdung Lp phiên: thit lp, duy trì và NFS,SQL hubmtphiênlàmvic Session TransportLayer NetworkLayer DataLink Physical Applicationlayer:ñâylàlpcaonhttrongmôhình.Nólànơimàngưis dnghocktnicácchươngtrìnhngdngvicácthtcchophéptruynhpvào mng. Presentationlayer:Lppresentationcungcpcácmãvàchcnăngñchuyn ñimàñưccungcpbilpngdng.Cácchcnăngñóñmborngdliut lpngdngtrongmththngcóthñưcñcbilpngdngcamththng khác.VD:dùngñmãhoádliutlpngdng:nhưmãhoánhjpeg,gif.Mãñó chophéptacóthhinlêntrangweb. Sessionlayer:ñưcsdngñthitlp,duytrìvàktthúcphiênlàmvic giacáclppresentation.Victraoñithôngtinlpnàybaogmyêucudchv vàñápngyêucucacácngdngtrênthitbkhác. Cáclpdưi. 4lpdưicamôhìnhOSIsdngññnhnghĩalàmthnàoñdliuñưc truynñitrongcácdâynivtlý,cácthitbmngvàñiñntrmñucuicuicùng làñncáclpngdng.Qunsáchnàytachquantâmñn4lpcui.Vàsxemxét tnglpmtcáchchititgiaothipgiacáclptrongmôhìnhOSI: Sdngphươngphápprotocalstackñktnigiahaithitbtrongmng.Protocal stacklàmttphpcácquyñnhdùngññnhnghĩalàmthnàoñdliutruyn quamng. Vídvi:TCP/IPmiLayerchophépdliutruynqua.Cáclpñótraoñicác thôngtinñcungcpcucliênlcgiahaithitbtrongmng.Cáclpgiaotipvi nhausdngProtocalDataUnit(PDU).ThôngtinñiukhincaPDUñưcthêm 4
  6. Simpo vàovidliulptrên.VàthôngtinñiukhinPDF Merge and Split Unregistered Version - nàynmtrongtrưnggilàtrưng headervàtrailer. Hình13Dataencapsulation Application Presentation UpperLayerData Session TCPHeader UpperLayerData Transport Segment IPHeader Data Network Packet LLCHeader Data FCS DataLink Frame MACHeader Data FCS Physical Bits 0101110101001000010 1.2.HgiaothcTCP/IP CáctngcagiaothcTCP/IPsovicctngcamôhìnhOSI Application:Xácnhnquyn,néndliuvàcácdchvchongưidùng Transport:Xlýdliugiacáchthngvacungcpvictruycpmngchocác ngdng Network:Tìmñưngchocácpacket 5
  7. Simpo Link:McOShoccácthitbgiaotipmngtrênmPDF Merge and Split Unregistered Version - tmáytính MtsñimkhácnhaucaTCP/IPvàmôhìnhOSI +LpngdngtrongTCP/IPxlýchcnăngcalp5,6,7trongmôhìnhOSI +LptransporttrongTCP/IPcungcpcchUDPtruynkhôngtincy,transport trongOSIluônñmbotruyntincy +TCP/IPlàmttpcacácprotocols(mtbgiaothc) +TCP/IPxâydngtrưcOSI QuytrìnhñónggóidliutrongmôhìnhTCP/IPnhưsau: 1.3.SosánhgiahaigiaothcTCPvàUDP 6
  8. Simpo PDF Merge and Split Unregistered Version - 1.4.Cnggiaothc Làmtsnămtrongkhong1 65535dùngñphânbitgia2ngdngmng vinhaugnviñachIPvàSocket Mtscngvàcácgiaothcthôngdng: +FTP:21 +Telnet:23 +SMTP:25 +POP3:110 +HTTP:80 1.5.ðachIP,cácñachIPdànhriêng 0 1 2 3 4 8 16 24 Class A 0 Netid Hostid Class B 1 0 Netid Hostid Class C 1 1 0 Netid Hostid Class D 1 1 1 0 Multicast address Class E 1 1 1 1 0 Reverved for future use 7
  9. Simpo PDF Merge and Split Unregistered Version - 1.6.ðachtênmin:loiA,loiMX 1.7.Mtsgiaothctngngdng:HTTP,SMTP,POP3,FTP Chúngtasnghiêncuchititcácgiaothcnàychương3 8
  10. Simpo PDF Merge and Split Unregistered Version - CHƯƠNG2:LPTRÌNHMNGTRONG.NETFRAMEWORK 2.1.Sockethưngktni(TCPSocket) Socketlàmtgiaodinlptrìnhngdng(API)mng Thôngquagiaodinnàychúngtacóthlptrìnhñiukhinvictruynthônggia haimáysdngcácgiaothcmcthplàTCP,UDP Socketlàstrutưnghoámccao,cóthtưngtưngnónhưlàthitbtruyn thônghaichiugi–nhndliugiahaimáytínhvinhau.  CácloiSocket  Sockethưngktni(TCPSocket)  Socketkhônghưngktni(UDPSocket)  RawSocket  ðcñimcaSockethưngktni  Có1ñưngktniogia2tintrình  Mttrong2tintrìnhphiñitintrìnhkiayêucuktni.  CóthsdngñliênlctheomôhìnhClient/Server  TrongmôhìnhClient/ServerthìServerlngnghevàchpnhnmtyêu cuktni  Mithôngñipgiñucóxácnhntrv  Cácgóitinchuynñitunt  ðcñimcaSocketkhônghưngktni  Haitintrìnhliênlcvinhaukhôngktnitrctip  Thôngñipgiñiphikèmtheoñachcangưinhn  Thôngñipcóthginhiuln  Ngưigikhôngchcchnthôngñiptitayngưinhn  Thôngñipgisaucóthñnñíchtrưcthôngñipgitrưcñó.  ShiucngcaSocket 9
  11. Simpo PDF Merge andðcóththchincáccucgiaotip,mttrongh Split Unregistered Version - quátrìnhphicông bshiucngcasocketmàmìnhsdng.  Micnggiaotipthhinmtñachxácñnhtronghthng.Khiquá trìnhñưcgánmtshiucng,nócóthnhndliugiñncng nàytcácquátrìnhkhác.  Quátrìnhcònlicũngyêucutoramtsocket. 2.1.1.GiithiuvNameSpaceSystem.NetvàSystem.Net.Sockets  Cungcpmtgiaodinlptrìnhñơnginchortnhiucácgiaothcmng.  Córtnhiulpñlptrình  TaquantâmlpIPAdress,IPEndPoint,DNS,  LpIPAdress  MtsFieldcnchúý:  Any:CungcpmtñachIPñchrarngServerphilngnghetrên ttccácCardmng  Broadcast:CungcpmtñachIPqungbá  Loopback:TrvmtñachIPlp  AdressFamily:TrvhñachcaIPhinhành  LpIPAddress  Mtsphươngthccnchúý:  Phươngthckhito  IPAddress(Byte[])  IPAddress(Int64)  IsLoopback:Chobitñachcóphiñachlpkhông  Parse:ChuynIPdngxâuvIPchun  ToString:TrñachIPvdngxâu  TryParse:KimtraIPdngxâucóhplkhông?  LpIPEndPoint  Mtsphươngthccnchúý:  Phươngthckhito  IPEndPoint(Int64,Int32)  IPEndPoint(IPAddress,Int32)  Create :TomtEndPointtmtñachSocket  ToString :TrvñachIPvàshiucngtheokhuôndngðaCh: Cng,víd:192.168.1.1:8080  LpDNS  Mtsthànhphncalp:  HostName:Chobittêncamáyñưcphângii  GetHostAddress:TrvttcIPcamttrm  GetHostEntry:Giiñáptênhocñachtruynvàovàtrvñitưng IPHostEntry 10
  12. Simpo PDF Merge andGetHostName:Lyvtêncamáytínhccb Split Unregistered Version -  NameSpaceSystem.Net.Sockets  Mtslphaydùng:TcpClient,UdpClient,TcpListener,Socket, NetworkStream,  ðtoraSocket  Socket(AddressFamily af ,SocketType st ,ProtocolType pt ) SocketType Protocoltype Description Dgram Udp Connectionlesscommunication Stream Tcp Connectionoriented communication Raw Icmp InternetControlMessage Protocol Raw Raw PlainIPpacketcommunication usingSystem.Net; usingSystem.Net.Sockets; classSockProp{ publicstaticvoidMain(){ IPAddressia=IPAddress.Parse("127.0.0.1"); IPEndPointie=newIPEndPoint(ia,8000); Sockettest=newSocket(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("newBlocking:{0}",test.Blocking); Console.WriteLine("Connected:{0}",test.Connected); test.Bind(ie); IPEndPointiep=(IPEndPoint)test.LocalEndPoint; Console.WriteLine("LocalEndPoint:{0}",iep.ToString()); test.Close(); Console.ReadKey(); } } 2.1.2.Vitchươngtrìnhchophíamáych  Vitchươngtrìnhchophíamáych  TomtSocket  LiênktvimtIPEndPointccb  Lngnghektni  Chpnhnktni  Ginhndliutheogiaothcñãthitk 11
  13. Simpo PDF Merge andðóngktnisaukhiñãhoànthànhvàtrlitrng Split Unregistered Version - tháilngnghech ktnimi  Vitchươngtrìnhchophíamáych IPEndPointipep=newIPEndPoint(IPAddress.Any,9050); Socketnewsock=Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Socketclient=newsock.Accept(); //Ginhndliutheogiaothcñãthitk . newsock.Close(); ChươngtrìnhServer: usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; classServer{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),2008); Socketserver=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); server.Bind(iep); server.Listen(10); Console.WriteLine("Choketnoituclient"); Socketclient=server.Accept(); Console.WriteLine("Chapnhanketnoitu:{0}", client.RemoteEndPoint.ToString()); strings="ChaobandenvoiServer"; //Chuyenchuoisthanhmangbyte byte[]data=newbyte[1024]; data=Encoding.ASCII.GetBytes(s); //guinhandulieutheogiaothucdathietke client.Send(data,data.Length,SocketFlags.None); while(true){ data=newbyte[1024]; intrecv=client.Receive(data); if(recv==0)break; //ChuyenmangbyteDatathanhchuoivainramanhinh s=Encoding.ASCII.GetString(data,0,recv); Console.WriteLine("Clienguilen:{0}",s); //NeuchuoinhanduoclaQuitthithoat if(s.ToUpper().Equals("QUIT"))break; //Guitralaichoclientchuois s=s.ToUpper(); data=newbyte[1024]; 12
  14. Simpo data=Encoding.ASCII.GetBytes(s);PDF Merge and Split Unregistered Version - client.Send(data,data.Length,SocketFlags.None); } client.Shutdown(SocketShutdown.Both); client.Close(); server.Close(); } } 2.1.3.Vitchươngtrìnhchophíamáykhách  Vitchươngtrìnhchophíamáykhách  XácñnhñachcaServer  ToSocket  KtniñnServer  Ginhndliutheogiaothcñãthitk  ðóngSocket  Vitchươngtrìnhchophíamáykhách IPEndPointipep=newIPEndPoint(Ipaddress.Parse("192.168.1.6"),9050); Socketserver=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); server.Connect(ipep); ChươngtrìnhClient: usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; classClient{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),2008); Socketclient=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); client.Connect(iep); byte[]data=newbyte[1024]; intrecv=client.Receive(data); strings=Encoding.ASCII.GetString(data,0,recv); Console.WriteLine("Servergui:{0}",s); stringinput; while(true){ input=Console.ReadLine(); //Chuyeninputthanhmangbyteguilenchoserver data=newbyte[1024]; data=Encoding.ASCII.GetBytes(input); client.Send(data,data.Length,SocketFlags.None); if(input.ToUpper().Equals("QUIT"))break; data=newbyte[1024]; recv=client.Receive(data); 13
  15. Simpo s=Encoding.ASCII.GetString(data,0,rePDF Merge and Split Unregistered Version - Console.WriteLine("Servergui:{0}",s); } client.Disconnect(true); client.Close(); } } 2.1.4.SdngcáclungnhpxutviSocket TSockettacóthtoralungñnhpxutviSocketñólàsdnglp NetworkStream Property Description CanRead IstrueiftheNetworkStreamsupportsreading CanSeek IsalwaysfalseforNetworkStreams CanWrite IstrueiftheNetworkStreamsupportswriting DataAvailable Istrueifthereisdataavailabletoberead VídchươngtrìnhClient/ServersdngNetworkStreamñgivànhndliu ChươngtrìnhClientsdngNetworkStream: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; 14
  16. Simpo classProgram{PDF Merge and Split Unregistered Version - staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),2009); Socketclient=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); client.Connect(iep); NetworkStreamns=newNetworkStream(client); byte[]data=newbyte[1024]; while(true){ stringinput=Console.ReadLine(); data=Encoding.ASCII.GetBytes(input); ns.Write(data,0,data.Length); if(input.ToUpper().Equals("QUIT"))break; data=newbyte[1024]; intrec=ns.Read(data,0,data.Length); strings=Encoding.ASCII.GetString(data,0,rec); Console.WriteLine(s); } client.Close(); } } ChươngtrìnhServersdngNetworkStream: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; classProgram{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),2009); Socketserver=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); server.Bind(iep); server.Listen(10); Socketclient=server.Accept(); byte[]data; NetworkStreamns=newNetworkStream(client); while(true){ data=newbyte[1024]; intrec=ns.Read(data,0,data.Length); strings=Encoding.ASCII.GetString(data,0,rec); Console.WriteLine(s); data=newbyte[1024]; s=s.ToUpper(); if(s.Equals("QUIT"))break; data=Encoding.ASCII.GetBytes(s); ns.Write(data,0,data.Length); } 15
  17. Simpo client.Close();PDF Merge and Split Unregistered Version - server.Close(); } } TrêncscaNetworkStreamtacóthnithêmcáclungñnhpxuttheohưng kýtnhưStreamReader,StreamWriter SauñâylàmtvídvchươngtrìnhClient/Serversdnglungnhpxut,chương trìnhServerchépphépClientgilênyêucu,nuyêuculàGetDatekhôngphânbit chhoachthưngthìServertrvchoClientngàyhinti,nuyêuculàGetTime khôngphanbithoathưngthìServertrvgihinti,nulàQuitthìServerngt ktniviClient,khôngphicáctrưnghptrênthìthôngbáokhônghiulênh. ChươngtrìnhphíaClient: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.IO; usingSystem.Threading; classDateTimeClient{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),9999); Socketclient=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); client.Connect(iep); NetworkStreamns=newNetworkStream(client); StreamReadersr=newStreamReader(ns); StreamWritersw=newStreamWriter(ns); while(true){ stringinput=Console.ReadLine(); sw.WriteLine(input); sw.Flush(); if(input.ToUpper().Equals("QUIT"))break; stringkq=sr.ReadLine(); Console.WriteLine(kq); } sr.Close(); sw.Close(); ns.Close(); client.Close(); } } ChươngtrìnhphíaServer: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Net; 16
  18. Simpo usingSystem.Net.Sockets;PDF Merge and Split Unregistered Version - usingSystem.IO; classDateTimeServer{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),2009); Socketserver=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); server.Bind(iep); server.Listen(10); Socketclient=server.Accept(); NetworkStreamns=newNetworkStream(client); StreamReadersr=newStreamReader(ns StreamWritersw=newStreamWriter(ns); stringkq=""; while(true){ strings=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="Khonghieulenh"; sw.WriteLine(kq); sw.Flush(); } sr.Close(); sw.Close(); client.Close(); } } 2.2.Socketkhônghưngktni(UDPSocket)  Chươngtrìnhphíamáych  TomtSocket  LiênktvimtIPEndPointccb  Ginhndliutheogiaothcñãthitk  ðóngSocket  Chươngtrìnhphíamáykhách  XácñnhñachServer  ToSocket  Ginhndliutheogiaothcñãthitk  ðóngSocket 2.2.1.Vitchươngtrìnhchophíamáych usingSystem; 17
  19. Simpo usingSystem.Collections.Generic;PDF Merge and Split Unregistered Version - usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; classProgram{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),2008); Socketserver=newSocket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); server.Bind(iep); //taoramotEndpottuxadenhandulieuve IPEndPointRemoteEp=newIPEndPoint(IPAddress.Any,0); EndPointremote=(EndPoint)RemoteEp; byte[]data=newbyte[1024]; intrecv=server.ReceiveFrom(data,refremote); strings=Encoding.ASCII.GetString(data,0,recv); Console.WriteLine("nhanvetuClient:{0}",s); data=Encoding.ASCII.GetBytes("Chaoclient"); server.SendTo(data,remote); while(true){ data=newbyte[1024]; recv=server.ReceiveFrom(data,refremote); s=Encoding.ASCII.GetString(data,0,recv); if(s.ToUpper().Equals("QUIT"))break; Console.WriteLine(s); data=newbyte[1024]; data=Encoding.ASCII.GetBytes(s); server.SendTo(data,0,data.Length,SocketFlags.None,remote); } server.Close(); } } 2.2.2.Vitchươngtrìnhchophíamáykhách usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; classProgram{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),2008); Socketclient=newSocket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); Strings="Chaoserver"; byte[]data=newbyte[1024]; data=Encoding.ASCII.GetBytes(s); client.SendTo(data,iep); EndPointremote=(EndPoint)iep; 18
  20. Simpo data=newbyte[1024];PDF Merge and Split Unregistered Version - intrecv=client.ReceiveFrom(data,refremote); s=Encoding.ASCII.GetString(data,0,recv); Console.WriteLine("NhanvetuServer{0}",s); while(true){ s=Console.ReadLine(); data=newbyte[1024]; data=Encoding.ASCII.GetBytes(s); client.SendTo(data,remote); if(s.ToUpper().Equals("QUIT"))break; data=newbyte[1024]; recv=client.ReceiveFrom(data,refremote); s=Encoding.ASCII.GetString(data,0,recv); Console.WriteLine(s); } client.Close(); } } SdngSocketkhônghưngktnivitchươngtrìnhchatgiưa2máynhư sau:(SaunàychúngtacóthsdnglpUdpClient) usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Threading; publicpartialclassForm1:Form{ privateSocketudp1; privateIPEndPointipremote,iplocal; publicForm1(){ InitializeComponent(); CheckForIllegalCrossThreadCalls=false; } privatevoidbtStart_Click(objectsender,EventArgse){ udp1=newSocket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); iplocal=newIPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(txtLocalPort.Text)); udp1.Bind(iplocal); ipremote=newIPEndPoint(IPAddress.Parse(txtIp.Text), int.Parse(txtRemotePort.Text)); Threadtuyen=newThread(newThreadStart(NhanDL)); tuyen.Start(); 19
  21. Simpo }PDF Merge and Split Unregistered Version - privatevoidbtSend_Click(objectsender,EventArgse){ byte[]data=newbyte[1024]; data=Encoding.ASCII.GetBytes(txtSend.Text); udp1.SendTo(data,ipremote); } privatevoidNhanDL(){ while(true){ byte[]data=newbyte[1024]; IPEndPointipe=newIPEndPoint(IPAddress.Any,0); EndPointremote=(EndPoint)ipe; intrec=udp1.ReceiveFrom(data,refremote); strings=Encoding.ASCII.GetString(data,0,rec); txtNoidung.Text+=s+"\r\n"; } } privatevoidbutton1_Click(objectsender,EventArgse){ MessageBox.Show(txtSend.Text.Substring(0,txtSend.Text.IndexOf(""))); } } 2.2.3.SdnglpSystem.IO.MemoryStreamñtovùngñmnhpxut 2.3.SdngcáclphtrñưcxâydngtlpSoket 20
  22. Simpo 2.3.1.LpTCPClientPDF Merge and Split Unregistered Version - McñíchcalpUDPClienttrênlàdùngcholptrìnhvigiaothcUDP, vigiaothcnàythìhaibênkhôngcnphithitlpktnitrưckhigidovymc ñtincykhôngcao.ðñmboñtincytrongcácngdngmng,ngưitacòn dùng mt giao thc khác, gi là giao thc có kt ni : TCP (Transport Control Protocol).TrênInternetchyulàdùngloigiaothcnày,vídnhưTelnet,HTTP, SMTP,POP3 ðlptrìnhtheogiaothcTCP,MS.NETcungcphailpcótênlà TCPClientvàTCPListener. CácthànhphncalpTcpClient +Phươngthckhito: ConstructorMethod Name Description TcpClient() TomtñitưngTcpClient .Chưañtthôngsgì. TcpClient TomtTcpClient vàgnchonómtEndPointccb. (IPEndPoint) (Gánñachmáyccbvàshiucngñsdngtrao ñithôngtinvsau) TcpClient TomtñitưngTcpClient vàktniñnmtmáycó (RemoteHost:String, ñachvàshiucngñưctruynvào RemoteHostcó Int32) thlàñachIPchunhoctênmáy. +Mtsthuctính: Name Description Available Chobitsbyteñãnhnvtmngvàcósn ññc. Client TrvSocketngviTCPClienthinhành. Connected TrngtháichobitñãktniñưcñnServerhaychưa? +Mtsphươngthc: Name Description Close GiiphóngñitưngTcpClient nhưng khôngñóngktni. Connect KtniñnmtmáyTCPkháccóTênvà (RemoteHost, shiucng. Port) 21
  23. Simpo PDF Merge and Split Unregistered Version - GetStream TrvNetworkStream ñtñógiúpta gihaynhndliu.(Thưnglàmtham skhitoStreamReadervà StreamWriter). Khi ñã gn vào StreamReader và StreamWriterrithìtacóthgivànhn d liu thông qua các phương thc Readln, writeline tương ng ca các lp này. TasdnglpTcpClientvitlichươngtrìnhDateTimeClientnhưsau: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.IO; usingSystem.Threading; classDateTimeClient{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),9999); TcpClientclient=newTcpClient(); client.Connect(iep); StreamReadersr=newStreamReader(client.GetStream()); StreamWritersw=newStreamWriter(client.GetStream()); while(true){ stringinput=Console.ReadLine(); sw.WriteLine(input); sw.Flush(); if(input.ToUpper().Equals("QUIT"))break; stringkq=sr.ReadLine(); Console.WriteLine(kq); } sr.Close(); sw.Close(); client.Close(); } } 2.3.2.LpTCPListener TCPListernerlà mtlpcho phép ngưilptrìnhcó th xây dng các ng dng Server (Ví d như SMTP Server, FTP Server, DNS Server, POP3 Server hay servertñnhnghĩa .).ngdngserverkhácvingdngClientchnóluôn luônthchinlngnghevàchpnhncácktniñntClient. 22
  24. Simpo CácthànhphncalpTcpListener:PDF Merge and Split Unregistered Version - +Phươngthckhito: Constructormethod Name Description TcpListener(Port: TomtTcpListener vàlngngheticngchñnh. Int32) TcpListener TomtTcpListener vigiátrEndpointtruynvào. (IPEndPoint) TcpListener TomtTcpListener vàlngnghecácktniñnti (IPAddress,Int32) ñachIPvàcngchñnh. +Cácphươngthckhác Name Description AcceptSocket Chpnhnmtyêucuktniñangch. AcceptTcpClient Chpnhnmtyêucuktniñangch.(ngdngs dngtilnhnàychoñnkhinàocómtktniñn) Pending Chobitliucóktninàoñangchñikhông?(True =có). Start Btñulngnghecácyêucuktni. Stop Dngvicnghe. SdnglpTcpListenertavitlichươngtrìnhDateTimeServernhưsau: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.IO; classDateTimeServer{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),2009); TcpListenerserver=newTcpListener(iep); server.Start(); TcpClientclient=server.AcceptTcpClient(); StreamReadersr=newStreamReader(client.GetStream()); StreamWritersw=newStreamWriter(client.GetStream()); stringkq=""; while(true){ 23
  25. Simpo strings=sr.ReadLine();PDF Merge and Split Unregistered Version - 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="Khonghieulenh"; sw.WriteLine(kq); sw.Flush(); } sr.Close(); sw.Close(); client.Close(); } } 2.3.3.LpUDPClient GiaothøcUDP(UserDatagramProtocolhayUserDefineProtocol)lmétgiaothøc phikÕtnèi(Connectionless)cãnghÜalmétbªncãthÓgöid÷liÖuchobªnkiamkh«ngcÇn biÕtlbªn®ã®s½nsnghaych−a?(Nãic¸chkh¸clkh«ngcÇnthiÕtlËpkÕtnèigi÷ahai bªnkhitiÕnhnhtrao®æith«ngtin).Giaothøcnykh«ngtincËyb»nggiaothøcTCPnh−ng tèc®él¹inhanhvdÔci®Æt.Ngoira,víigiaothøcUDPtacßncãthÓgöic¸cgãitinqu¶ng b¸(Broadcast)cho®ångthêinhiÒum¸y. Trong.NET,líp UDPClient (n»mtrong System.Net.Sockets )®ãnggãic¸cchøcn¨ng cñagiaothøcUDP. Constructor methosd Description UdpClient() T¹omét®èit−îng(thÓhiÖn)míicñalíp UDPClient. UdpClient(AddressFamily) T¹omét®èit−îng(thÓhiÖn)míicñalíp UDPClient.Thuécmétdßng®ÞachØ (AddressFamily)®−îcchØ®Þnh. UdpClient(Int32) T¹omét UdpClient vg¾n(bind)métcængchonã. UdpClient(IPEndPoint) T¹omét UdpClient vg¾n(bind)métIPEndpoint (g¸n®ÞachØIPvcæng)chonã. UdpClient(Int32,AddressFamily) T¹omét UdpClient vg¸nsèhiÖucæng, AddressFamily 24
  26. Simpo PDF Merge and Split Unregistered Version - UdpClient(String,Int32) T¹omét UdpClient vthiÕtlËpvíiméttr¹mtõxa mÆc®Þnh. PUBLIC Method Name Description BeginReceive NhËnd÷liÖuKh«ng®ångbétõm¸yëxa. BeginSend Göikh«ng®ångbéd÷liÖutíim¸yëxa Close §ãngkÕtnèi. Connect ThiÕtlËpmétDefaultremotehost. EndReceive KÕtthócnhËnd÷liÖukh«ng®ångbéëtrªn EndSend KÕtthócviÖcgöid÷liÖukh«ng®ångbéëtrªn Receive NhËn d÷ liÖu (®ång bé) do m¸y ë xa göi. (§ång bé cã nghÜalc¸clÖnhngaysaulÖnhReceivechØ®−îcthùcthinÕu Receive ® nhËn ®−îc d÷ liÖu vÒ . Cßn nÕu nã ch−a nhËn ®−îc–dïchØmétchót–th×nãvÉncøchê(blocking)) Send Göi d÷ liÖu (®ång bé) cho m¸y ë xa. VídsdngUdpClientvitchươngtrìnhChatgia2máy: Dochươngtrình2máylànhưnhautachcnvitmtchươngtrìnhcopyrañs dng. Hìnhnhcanónhưsau: usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; 25
  27. Simpo usingSystem.Text;PDF Merge and Split Unregistered Version - usingSystem.Windows.Forms; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Threading; namespaceUdpChat{ publicpartialclassForm1:Form{ publicForm1(){ InitializeComponent(); CheckForIllegalCrossThreadCalls=false; } privatevoidbtSend_Click(objectsender,EventArgse){ UdpClientsend=newUdpClient(); IPEndPointiepRemote=newIPEndPoint(IPAddress.Parse(txtIp.Text), int.Parse(txtRemotePort.Text)); byte[]data=newbyte[1024]; data=Encoding.UTF8.GetBytes(txtSend.Text); send.Send(data,data.Length,iepRemote); txtReceive.Text+="Sender:"+txtSend.Text+"\r\n"; txtSend.Clear(); if(txtSend.Text.ToUpper().Equals("QUIT"))this.Dispose(); } privatevoidbtConnect_Click(objectsender,EventArgse){ Threadtuyen=newThread(newThreadStart(NhanDl)); tuyen.Start(); } privatevoidNhanDl(){ UdpClientreceiver=newUdpClient(int.Parse(txtLocalPort.Text)); IPEndPointiep=newIPEndPoint(IPAddress.Any,0); while(true){ byte[]data=newbyte[1024]; data=receiver.Receive(refiep); strings=Encoding.UTF8.GetString(data); if(s.Trim().ToUpper().Equals("QUIT"))break; txtReceive.Text+="Receiver:"+s+"\r\n"; } } } } 2.4.Socketkhôngñngb 2.4.1.Môhìnhxlýskincawindows 26
  28. Simpo PDF Merge MôhìnhxlýskincaWindowsñưcthhinqu and Split Unregistered Version - hìnhsau: Nhưvythôngquamôhìnhnàytacóthynhimchomtthtcnàoñóthc hinkhiskinsyratrêncácControl Víd: usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; namespaceEventDemo{ publicpartialclassForm1:Form{ publicForm1(){ InitializeComponent(); button1.Click+=newEventHandler(NhanTiep); } privatevoidbutton1_Click(objectsender,EventArgse){ MessageBox.Show("Bacdanhanem"); } privatevoidNhanTiep(objectsender,EventArgse){ MessageBox.Show("Baclainhanemroi"); } } } vídtrênchúngtangoàiskinClickcabutton1chúngtathêmmtx kinkhibutton1ñưcnhnñólàskinNhanTiep. 2.4.2.SdngSocketkhôngñngb ðlptrìnhkhôngñngbviSocketchúngtasdngcácphươngthccho vicsdngbtñngb 27
  29. Simpo PDF Merge Cácphươngthcchoviclptrìnhbtñngbñư and Split Unregistered Version - chialàm2lithưngbt ñubngBeginvàEnd:  PhươngthcbtñubngBegin,btñumtchcnăngvàñưcñăng kýviphươngthcAsyncCallback  BtñubngEndchchcnănghoànthànhkhiAsyncCallbackñưc gi. RequestsStartedBy DescriptionofRequest RequestsEndedBY BeginAccept() To accept an incoming EndAccept() connection BeginConnect() To connect to a remote EndConnect() host BeginReceive() To retrieve data from a EndReceive() socket BeginReceiveFrom() To retrieve data from a EndReceiveFrom() specific remote host BeginSend() To send data from a EndSend() socket BeginSendTo() To send data to a EndSendTo() specific remote host ðchpnhnktnibtñngbtasdngphươngthcBeginAccept()và EndAccept()nhưsau:  PhươngthcBeginAccept()vàEndAccept() IAsyncResultBeginAccept(AsyncCallbackcallback,objectstate) SocketEndAccept(IAsyncResultiar);  Thưngñưcdùngnhưsau: Socketsock=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); IPEndPointiep=newIPEndPoint(IPAddress.Any,9050); sock.Bind(iep); sock.Listen(5); sock.BeginAccept(newAsyncCallback(CallAccept),sock); TrongñóphươngthcCallAcceptthưngñưcvitnhưsau: privatestaticvoidCallAccept(IAsyncResultiar){ Socketserver=(Socket)iar.AsyncState; Socketclient=server.EndAccept(iar); ... } ðthitlpktnitheocáchbtñngbchúngtasdngphươngthc BeginConnect()vàEndConnect()nhưsau:  PhươngthcBeginConnect()vàEndConnect() 28
  30. Simpo PDF Merge Socketnewsock=newSocket(AddressFamily.InterNetwor and Split Unregistered Version - SocketType.Stream,ProtocolType.Tcp); IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),9050); newsock.BeginConnect(iep,newAsyncCallback(Connected),newsock); TrongñóphươngthcConnectedthưngñưcvitnhưsau: publicstaticvoidConnected(IAsyncResultiar){ Socketsock=(Socket)iar.AsyncState; try{ sock.EndConnect(iar); }catch(SocketException){ Console.WriteLine("Unabletoconnecttohost"); } } ðgidliubtñngbchúngtalàmnhưsau: +PhươngthcBeginSend()vàEndSend() +BeginSend() IAsyncResultBeginSend(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() intEndSend(IAsyncResultiar) TrongñóphươngthcSendDatathưngñưcvitnhưsau: privatestaticvoidSendData(IAsyncResultiar){ Socketserver=(Socket)iar.AsyncState; intsent=server.EndSend(iar); } Tươngtnhưgiaothchưngktninutasdnggidliutheogiaothc khônghưngktnichúngtacũngthchintươngtnhưsau:  PhươngthcBeginSendTo()vàEndSendTo() IAsyncResultBeginSendTo(byte[]buffer,intoffset,intsize,SocketFlags sockflag,EndPointep,AsyncCallbackcallback,objectstate) Víd: IPEndPointiep=newEndPoint(IPAddress.Parse("192.168.1.6"),9050); sock.BeginSendTo(data,0,data.Length,SocketFlags.None,iep,new AsynCallback(SendDataTo),sock); intEndSendTo(IAsyncResultiar) ðnhndliubtñngbtathchinnhưsau: +Nhndliuvigiaothchưngktni:  PhươngthcBeginReceivevàEndReceive() 29
  31. Simpo PDF Merge sock.BeginReceive(data,0,data.Length,SocketFlags and Split Unregistered Version - new AsyncCallback(ReceivedData),sock); ViReceivedDatañưcñnhnghĩanhưsau: voidReceivedData(IAsyncResultiar){ Socketremote=(Socket)iar.AsyncState; intrecv=remote.EndReceive(iar); stringreceivedData=Encoding.ASCII.GetString(data,0, recv); Console.WriteLine(receivedData); } +Nhndliubtñngbvigiaothckhônghưngktni.  PhươngthcBeginReceiveFrom()andEndReceiveFrom() sock.BeginReceive(data,0,data.Length,SocketFlags.None,refiep,new AsyncCallback(ReceiveData),sock); voidReceiveData(IasyncResultiar){ Socketremote=(Socket)iar.AsyncState; intrecv=remote.EndReceiveFrom(iar); stringstringData=Encoding.ASCII.GetString(data,0, recv); Console.WriteLine(stringData); } 2.4.3.VídvSocketkhôngñngb Sauñâychúngtassdngcácphươngthckhôngñngbvitchươngtrình Client/ServertheoSocketbtñngb,mikhiClientgidliulênServer,nósin ravàgitrlichoClient.Môhìnhcaclient/serversdngcácphươngthcbt ñngbnhưsau: 30
  32. Simpo PDF Merge and Split Unregistered Version - ChươngtrìnhphíaClient: usingSystem; usingSystem.Drawing; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Text; usingSystem.Windows.Forms; classAsyncTcpClient:Form { privateTextBoxnewText; privateTextBoxconStatus; privateListBoxresults; privateSocketclient; privatebyte[]data=newbyte[1024]; privateintsize=1024; publicAsyncTcpClient() { Text="AsynchronousTCPClient"; Size=newSize(400,380); Labellabel1=newLabel(); label1.Parent=this; label1.Text="Entertextstring:"; label1.AutoSize=true; label1.Location=newPoint(10,30); newText=newTextBox(); newText.Parent=this; newText.Size=newSize(200,2*Font.Height); newText.Location=newPoint(10,55); results=newListBox(); results.Parent=this; results.Location=newPoint(10,85); results.Size=newSize(360,18*Font.Height); Labellabel2=newLabel(); label2.Parent=this; 31
  33. Simpo label2.Text="ConnectionStatus:";PDF Merge and Split Unregistered Version - label2.AutoSize=true; label2.Location=newPoint(10,330); conStatus=newTextBox(); conStatus.Parent=this; conStatus.Text="Disconnected"; conStatus.Size=newSize(200,2*Font.Height); conStatus.Location=newPoint(110,325); Buttonsendit=newButton(); sendit.Parent=this; sendit.Text="Send"; sendit.Location=newPoint(220,52); sendit.Size=newSize(5*Font.Height,2*Font.Height); sendit.Click+=newEventHandler(ButtonSendOnClick); Buttonconnect=newButton(); connect.Parent=this; connect.Text="Connect"; connect.Location=newPoint(295,20); connect.Size=newSize(6*Font.Height,2*Font.Height); connect.Click+=newEventHandler(ButtonConnectOnClick); Buttondiscon=newButton(); discon.Parent=this; discon.Text="Disconnect"; discon.Location=newPoint(295,52); discon.Size=newSize(6*Font.Height,2*Font.Height); discon.Click+=newEventHandler(ButtonDisconOnClick); } voidButtonConnectOnClick(objectobj,EventArgsea) { conStatus.Text="Connecting "; Socketnewsock=newSocket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),9050); newsock.BeginConnect(iep,newAsyncCallback(Connected),newsock); } voidButtonSendOnClick(objectobj,EventArgsea) { byte[]message=Encoding.ASCII.GetBytes(newText.Text); newText.Clear(); client.BeginSend(message,0,message.Length,SocketFlags.None, newAsyncCallback(SendData),client); } voidButtonDisconOnClick(objectobj,EventArgsea) { client.Close(); conStatus.Text="Disconnected"; } voidConnected(IAsyncResultiar) { 32
  34. Simpo client=(Socket)iar.AsyncState;PDF Merge and Split Unregistered Version - try { client.EndConnect(iar); conStatus.Text="Connectedto:"+client.RemoteEndPoint.ToString(); client.BeginReceive(data,0,size,SocketFlags.None, newAsyncCallback(ReceiveData),client); }catch(SocketException) { conStatus.Text="Errorconnecting"; } } voidReceiveData(IAsyncResultiar) { Socketremote=(Socket)iar.AsyncState; intrecv=remote.EndReceive(iar); stringstringData=Encoding.ASCII.GetString(data,0,recv); results.Items.Add(stringData); } voidSendData(IAsyncResultiar) { Socketremote=(Socket)iar.AsyncState; intsent=remote.EndSend(iar); remote.BeginReceive(data,0,size,SocketFlags.None, newAsyncCallback(ReceiveData),remote); } publicstaticvoidMain() { Application.Run(newAsyncTcpClient()); } } ChươngtrìnhphíaServer: usingSystem; usingSystem.Drawing; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Text; usingSystem.Windows.Forms; classAsyncTcpSrvr:Form { privateTextBoxconStatus; privateListBoxresults; privatebyte[]data=newbyte[1024]; privateintsize=1024; privateSocketserver; publicAsyncTcpSrvr() { Text="AsynchronousTCPServer"; Size=newSize(400,380); 33
  35. Simpo results=newListBox();PDF Merge and Split Unregistered Version - results.Parent=this; results.Location=newPoint(10,65); results.Size=newSize(350,20*Font.Height); Labellabel1=newLabel(); label1.Parent=this; label1.Text="Textreceivedfromclient:"; label1.AutoSize=true; label1.Location=newPoint(10,45); Labellabel2=newLabel(); label2.Parent=this; label2.Text="ConnectionStatus:"; label2.AutoSize=true; label2.Location=newPoint(10,330); conStatus=newTextBox(); conStatus.Parent=this; conStatus.Text="Waitingforclient "; conStatus.Size=newSize(200,2*Font.Height); conStatus.Location=newPoint(110,325); ButtonstopServer=newButton(); stopServer.Parent=this; stopServer.Text="StopServer"; stopServer.Location=newPoint(260,32); stopServer.Size=newSize(7*Font.Height,2*Font.Height); stopServer.Click+=newEventHandler(ButtonStopOnClick); server=newSocket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); IPEndPointiep=newIPEndPoint(IPAddress.Any,9050); server.Bind(iep); server.Listen(5); server.BeginAccept(newAsyncCallback(AcceptConn),server); } voidButtonStopOnClick(objectobj,EventArgsea) { Close(); } voidAcceptConn(IAsyncResultiar) { Socketoldserver=(Socket)iar.AsyncState; Socketclient=oldserver.EndAccept(iar); conStatus.Text="Connectedto:"+client.RemoteEndPoint.ToString(); stringstringData="Welcometomyserver"; byte[]message1=Encoding.ASCII.GetBytes(stringData); client.BeginSend(message1,0,message1.Length,SocketFlags.None, newAsyncCallback(SendData),client); } voidSendData(IAsyncResultiar) { Socketclient=(Socket)iar.AsyncState; 34
  36. Simpo intsent=client.EndSend(iar);PDF Merge and Split Unregistered Version - client.BeginReceive(data,0,size,SocketFlags.None, newAsyncCallback(ReceiveData),client); } voidReceiveData(IAsyncResultiar) { Socketclient=(Socket)iar.AsyncState; intrecv=client.EndReceive(iar); if(recv==0) { client.Close(); conStatus.Text="Waitingforclient "; server.BeginAccept(newAsyncCallback(AcceptConn),server); return; } stringreceivedData=Encoding.ASCII.GetString(data,0,recv); results.Items.Add(receivedData); byte[]message2=Encoding.ASCII.GetBytes(receivedData); client.BeginSend(message2,0,message2.Length,SocketFlags.None, newAsyncCallback(SendData),client); } publicstaticvoidMain() { Application.Run(newAsyncTcpSrvr()); } } 2.4.4.SdngcácphươngthcNonblocking ðlptrìnhbtñngbchúngtacóthsdngcácphươngthcNon– blokingnhưphươngthcPoll()vàphươngthcSelect: +PhươngthcPoll() boolPoll(intmicroseconds,SelectModemode);  SelectRead:Poll()trvtruenumttrongnhngñiukinsauñưc tho:  NuphươngthcAccept()thànhcông  NucódliutrênSocket  Nuktniñãñóng  SelectWrite:Poll()trvtruenuthomttrongnhngñiukinsau:  PhươngthcConnect()thànhcông  NucódliutrênSocketñgi  SelectError:Poll()trvtruenumttrongnhngñiukinsauñưc tho:  NuphươngthcConnect()thtbi  Nucódliungoàibăngthôngchungiñnnhưngthuctính OutOfBandInlinekhôngñưcthitlplàtrue. +PhươngthcSelect(): 35
  37. Simpo PDF Merge Socket.Select(IListcheckRead,IListcheckWrite,ILi and Split Unregistered Version - checkError,int microseconds) •checkRead monitorsthespecifiedsocketsfortheabilitytoreaddatafromthe socket. •checkWrite monitorsthespecifiedsocketsfortheabilitytowritedatatothe socket. •checkError monitorsthespecifiedsocketsforerrorconditions. VídngdngServersdngphươngthcPoll() usingSystem; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Text; classTcpPollSrvr { publicstaticvoidMain() { intrecv; byte[]data=newbyte[1024]; IPEndPointipep=newIPEndPoint(IPAddress.Any, 9050); Socketnewsock=new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waitingforaclient "); boolresult; inti=0; while(true) { i++; Console.WriteLine("pollingforaccept#{0} ",i); result=newsock.Poll(1000000,SelectMode.SelectRead); if(result) { break; } } Socketclient=newsock.Accept(); IPEndPointnewclient= (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connectedwith{0}atport{1}", newclient.Address,newclient.Port); stringwelcome="Welcometomytestserver"; data=Encoding.ASCII.GetBytes(welcome); client.Send(data,data.Length, SocketFlags.None); 36
  38. Simpo PDF Merge and Split Unregistered Version - i=0; while(true) { Console.WriteLine("pollingforreceive#{0} ",i); i++; result=client.Poll(3000000,SelectMode.SelectRead); if(result) { data=newbyte[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("Disconnectedfrom{0}", newclient.Address); client.Close(); newsock.Close(); } } SauñâychúngtasvitmtchươngtrìnhServersdngphươngthcSelect() ñchpnhn2ktniñntclientvàxlýtngktni. ChươngtrìnhSelectServer: usingSystem; usingSystem.Collections; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Text; classSelectTcpSrvr { publicstaticvoidMain() { ArrayListsockList=newArrayList(2); ArrayListcopyList=newArrayList(2); Socketmain=newSocket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); IPEndPointiep=newIPEndPoint(IPAddress.Any,9050); byte[]data=newbyte[1024]; stringstringData; 37
  39. Simpo intrecv;PDF Merge and Split Unregistered Version - main.Bind(iep); main.Listen(2); Console.WriteLine("Waitingfor2clients "); Socketclient1=main.Accept(); IPEndPointiep1=(IPEndPoint)client1.RemoteEndPoint; client1.Send(Encoding.ASCII.GetBytes("Welcometomyserver")); Console.WriteLine("Connectedto{0}",iep1.ToString()); sockList.Add(client1); Console.WriteLine("Waitingfor1moreclient "); Socketclient2=main.Accept(); IPEndPointiep2=(IPEndPoint)client2.RemoteEndPoint; client2.Send(Encoding.ASCII.GetBytes("Welcometomyserver")); Console.WriteLine("Connectedto{0}",iep2.ToString()); sockList.Add(client2); main.Close(); while(true) { copyList=newArrayList(sockList); Console.WriteLine("Monitoring{0}sockets ",copyList.Count); Socket.Select(copyList,null,null,10000000); foreach(SocketclientincopyList) { data=newbyte[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("Lastclientdisconnected,bye"); return; } } else client.Send(data,recv,SocketFlags.None); 38
  40. Simpo }PDF Merge and Split Unregistered Version - } } } ChươngtrìnhClient: usingSystem; usingSystem.Collections; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Text; classSelectTcpClient { publicstaticvoidMain() { Socketsock=newSocket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp); IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),9050); byte[]data=newbyte[1024]; stringstringData; intrecv; sock.Connect(iep); Console.WriteLine("Connectedtoserver"); 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=newbyte[1024]; recv=sock.Receive(data); stringData=Encoding.ASCII.GetString(data,0,recv); Console.WriteLine("Received:{0}",stringData); } sock.Close(); } } 2.5.SdngThreadtrongcácngdngmng 39
  41. Simpo MtskháinimPDF Merge and Split Unregistered Version - ðanhim(Multitasking):Làkhnănghñiêuhànhlàmnhiucôngvictimtthi ñim Tintrình(Process):Khichymtngdng,hñiuhànhscpphátriêngchong dngñóbnhvàcáctàinguyênkhác.Bnhvàtàinguyênvtlýriêngbitnày ñưcgilàmttintrình.Cáctàinguyênvàbnhcamttintrìnhthìchtin trìnhñóñưcphéptruycp. Tuyn(Thread):Tronghthng,mttintrìnhcóthcómthocnhiuchuithc hintáchbitnhauvàcóthchyñngthi.Michuithchinnàyñưcgilàmt tuyn(Thread).Trongmtngdng,ThreadkhitoñutiêngilàThreadsơcp hayThreadchính. 2.5.1.SdngThreadtrongchươngtrình.Net ðsdngThreadtrong.NettasdngNameSpaceSystem.Threading Mtsphươngthcthưngdùng PublicMethod Môt Name Abort() KtthúcThread Join() Bucchươngtrìnhphichchothreadktthúc(Block)thìmithchin tip(cáccâulnhñngsauJoin). Resume() Tiptcchythreadñãbtmngưngsuspended. Sleep() Staticmethod:Tmdngthreadtrongmtkhongthigian. Start() Btñuchy(khiñng)mtthread.Saukhigiphươngthcnày,trng tháicathreadchuynttrngtháihinhànhsangRunning. Suspend() Tmngưng(ngh)thread.(Phươngthcnàyñãbloikhiphiênbn VS.NET2005) Mtsthuctínhthưngdùng: PublicProperty Môt Name CurrentThread Thisstaticproperty:Trvthreadhinhànhñangchy. IsAlive Trvgiátrchobittrngtháithcthicathreadhinhành. IsBackground Setsorgetsgiátrchobitlàthreadlàbackgroundhayforeground thread. IsThreadPoolThread Getsavalueindicatingwhetherathreadispartofathreadpool. Priority Setsorgetsgiátrñchñnhñưutiên(dànhnhiuhayítCPUcho thread).Caonhtlà4,thpnhtlà0. 40
  42. Simpo PDF Merge and Split Unregistered Version - PublicProperty Môt Name ThreadState Lyvtrngtháicathread(ñangdng,hayñangchy ) TomttuyntrongC# ThreadnewThread=newThread(newThreadStart(newMethod)); . } voidnewMethod(){ ... } 2.5.2. SdngThreadtrongcácchươngtrìnhServer ðatuyênhayñưcngdngtrongcácchươngtrìnhServer,cácchươngtrình ñòihitimtthiñimchpnhnnhiuktniñntcácClient. ðcácchươngtrìnhServercóthxlýnhiuClienttimtthiñimtacó môhìnhngdngñatuynnhưsau: SauñâychúngtavitlichươngtrìnhDateTimeServercósdngThreadnhưsau: usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Threading; usingSystem.IO; classProgram{ staticvoidMain(string[]args){ IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),2009); TcpListenerserver=newTcpListener(iep); server.Start(); while(true){ 41
  43. Simpo //chapnhanketnoiPDF Merge and Split Unregistered Version - TcpClientclient=server.AcceptTcpClient(); //TaoratuyenmoidexulymoiClient newClientThread(client); } server.Stop(); } } classClientThread{ privateThreadtuyen; privateTcpClientclient; publicClientThread(TcpClientclient){ this.client=client; tuyen=newThread(newThreadStart(GuiNhanDL)); tuyen.Start(); } privatevoidGuiNhanDL(){ StreamReadersr=newStreamReader(client.GetStream()); StreamWritersw=newStreamWriter(client.GetStream()); stringkq=""; while(true) { strings=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="Khonghieulenh"; sw.WriteLine(kq); sw.Flush(); } client.Close(); } } 2.5.3.SdngThreadñgi/nhndliu ngdngñatuyntrongvicginhndliuchúngtavitchươngtrìnhChat theogiaothcTCPnhưsau: 42
  44. Simpo PDF Merge and Split Unregistered Version - ngdngmôhìnhxlýskincaWindowsvàñatuynvàSocketkhông ñngbtachcnvitmtchươngtrìnhsauñódchra,tachyngdngnhnListen nóslngnghetrongvaitròServercònkhitachyvànhnConnectnósñóngvai tròClientvàktnitiServer. Vănbnchươngtrìnhnhưsau: usingSystem; usingSystem.Drawing; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Text; usingSystem.Threading; 43
  45. Simpo usingSystem.Windows.Forms;PDF Merge and Split Unregistered Version - classTcpChat:Form { privatestaticTextBoxnewText; privatestaticListBoxresults; privatestaticSocketclient; privatestaticbyte[]data=newbyte[1024]; publicTcpChat() { Text="TCPChatProgram"; Size=newSize(400,380); Labellabel1=newLabel(); label1.Parent=this; label1.Text="Entertextstring:"; label1.AutoSize=true; label1.Location=newPoint(10,30); newText=newTextBox(); newText.Parent=this; newText.Size=newSize(200,2*Font.Height); newText.Location=newPoint(10,55); results=newListBox(); results.Parent=this; results.Location=newPoint(10,85); results.Size=newSize(360,18*Font.Height); Buttonsendit=newButton(); sendit.Parent=this; sendit.Text="Send"; sendit.Location=newPoint(220,52); sendit.Size=newSize(5*Font.Height,2*Font.Height); sendit.Click+=newEventHandler(ButtonSendOnClick); Buttonconnect=newButton(); connect.Parent=this; connect.Text="Connect"; connect.Location=newPoint(295,20); connect.Size=newSize(6*Font.Height,2*Font.Height); connect.Click+=newEventHandler(ButtonConnectOnClick); Buttonlisten=newButton(); listen.Parent=this; listen.Text="Listen"; listen.Location=newPoint(295,52); listen.Size=newSize(6*Font.Height,2*Font.Height); listen.Click+=newEventHandler(ButtonListenOnClick); } voidButtonListenOnClick(objectobj,EventArgsea) { results.Items.Add("Listeningforaclient "); Socketnewsock=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); 44
  46. Simpo IPEndPointiep=newIPEndPoint(IPAddress.Any,905PDF Merge and Split Unregistered Version - newsock.Bind(iep); newsock.Listen(5); newsock.BeginAccept(newAsyncCallback(AcceptConn),newsock); } voidButtonConnectOnClick(objectobj,EventArgsea) { results.Items.Add("Connecting "); client=newSocket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); IPEndPointiep=newIPEndPoint(IPAddress.Parse("127.0.0.1"),9050); client.BeginConnect(iep,newAsyncCallback(Connected),client); } voidButtonSendOnClick(objectobj,EventArgsea) { byte[]message=Encoding.ASCII.GetBytes(newText.Text); newText.Clear(); client.BeginSend(message,0,message.Length,0, newAsyncCallback(SendData),client); } voidAcceptConn(IAsyncResultiar) { Socketoldserver=(Socket)iar.AsyncState; client=oldserver.EndAccept(iar); results.Items.Add("Connectionfrom:"+client.RemoteEndPoint.ToString()); Threadreceiver=newThread(newThreadStart(ReceiveData)); receiver.Start(); } voidConnected(IAsyncResultiar) { try { client.EndConnect(iar); results.Items.Add("Connectedto:"+client.RemoteEndPoint.ToString()); Threadreceiver=newThread(newThreadStart(ReceiveData)); receiver.Start(); }catch(SocketException) { results.Items.Add("Errorconnecting"); } } voidSendData(IAsyncResultiar) { Socketremote=(Socket)iar.AsyncState; intsent=remote.EndSend(iar); } voidReceiveData() { intrecv; 45
  47. Simpo stringstringData;PDF Merge and Split Unregistered Version - 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("Connectionstopped"); return; } publicstaticvoidMain() { Application.Run(newTcpChat()); } } 2.5.4.SdngThreadPooltrongcácchươngtrình.Net Method Description BindHandle() Bindsanoperatingsystemhandletothe threadpool GetAvailableThreads() Getsthenumberofworkerthreads availableforuseinthethreadpool GetMaxThreads() Getsthemaximumnumberofworker threadsavailableinthethreadpool QueueUserWorkItem() Queuesauserdelegatetothethread pool RegisterWaitForSingleObject() Registersadelegatewaitingfora WaitHandleobject UnsafeQueueUserWorkItem() Queuesanunsafeuserdelegatetothe threadpoolbutdoesnotpropagatethe callingstackontotheworkerthread UnsafeRegisterWaitForSingleObject() Registersanunsafedelegatewaitingfor aWaitHandleobject using System; using System.Threading; class ThreadPoolSample { 46
  48. Simpo PDF public Merge static and Splitvoid Unregistered Main() Version - { 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.SdngThreadPooltrongcácchươngtrìnhServer using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; class ThreadPoolTcpSrvr { private TcpListener client; public ThreadPoolTcpSrvr() { client = new TcpListener(9050); client.Start(); Console.WriteLine("Waiting for clients "); while(true) { while (!client.Pending()) { Thread.Sleep(1000); } ConnectionThread newconnection = new ConnectionThread(); newconnection.threadListener = this.client; ThreadPool.QueueUserWorkItem(new WaitCallback(newconnection.HandleConnection)); } } public static void Main() { ThreadPoolTcpSrvr tpts = new ThreadPoolTcpSrvr(); 47
  49. Simpo PDF } Merge and Split Unregistered Version - } 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.KthutIPMulticasting 2.6.1.Broadcastinglàgì? Broadcast,tingVitgilàqungbá.Tronghthngmnghutuyn,qungbálà thutngdùngñchvicgimtgóithôngtinñnttcácnútmngtrongmng.ð thchinhìnhthcqungbá,ñachñncagóitinslàñachqungbá. Cóhailoilà:LocalBroadcastvàGlobalBroadcast 2.6.2.SdngBroadcastingñgidliuñnnhiumáytrongmngccb GigóidliuBroadcast usingSystem; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Text; classBadBroadcast{ publicstaticvoidMain(){ Socketsock=newSocket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp); IPEndPointiep=newIPEndPoint(IPAddress.Broadcast,9050); byte[]data=Encoding.ASCII.GetBytes("Thisisatestmessage"); sock.SendTo(data,iep); sock.Close(); } 48
  50. Simpo }PDF Merge and Split Unregistered Version - Chúngtaphithitlpnhưsau: classBroadcst{ publicstaticvoidMain(){ Socketsock=newSocket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); IPEndPointiep1=newIPEndPoint(IPAddress.Broadcast,9050); IPEndPointiep2=newIPEndPoint(IPAddress.Parse("192.168.1.255"),9050); stringhostname=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(); } } NhngóidliuBroadcast classRecvBroadcst{ publicstaticvoidMain(){ Socketsock=newSocket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); IPEndPointiep=newIPEndPoint(IPAddress.Any,9050); sock.Bind(iep);EndPointep=(EndPoint)iep; Console.WriteLine("Readytoreceive ");byte[]data=newbyte[1024]; intrecv=sock.ReceiveFrom(data,refep); stringstringData=Encoding.ASCII.GetString(data,0,recv); Console.WriteLine("received:{0}from:{1}",stringData,ep.ToString()); data=newbyte[1024];recv=sock.ReceiveFrom(data,refep); stringData=Encoding.ASCII.GetString(data,0,recv); Console.WriteLine("received:{0}from:{1}",stringData,ep.ToString()); sock.Close(); } } 2.6.3.Multicastinglàgì? Mtñachmulticastchophépthitbgidliutimttpxácñnhtrưccáchost, ñưcbitñnnhưcácnhómmulticast,trongcácmngconkhácnhau. MtsñachMulticast ðachmulticast Chcnăng 224.0.0.0 ðachcơs 224.0.0.1 Ttccáchthngtrênmngconnày 224.0.0.2 TtccácRoutertrênmngconnày 49
  51. Simpo PDF Merge and224.0.0.5 Split Unregistered CácDRtrongOSPF Version - 224.0.1.9 NhómñachRIPv2 224.0.1.24 NhómñachWINSserver Có2kthutMulticastñưcsdng +PeertoPeer +CentralServer 2.6.4.SocketMulticastingtrong.Net  SdngphươngthcSetSocketOption() 50
  52. Simpo PDF MergeSocketoptioncóthñưcsdngñ and Split Unregistered Version -  ThêmmtSocketvàonhómMulticast  LoimtSocketkhinhómMulticast  SetSocketOption(SocketOptionLevel,SocketOptionName,optionValue)  SocketOptionName  AddMembership  DropMembership  SdngphươngthcSetSocketOption()  Socketoptioncóthñưcsdngñ  optionValuelàmtñitưngcalpMulticastOption MulticastOption(IPAddress)MulticastOption(IPAddress,IPAddress)  VídthêmmtSocketvàonhómMulticast224.100.0.1 sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,new MulticastOption(IPAddress.Parse("224.100.0.1")); GidliuMulticast classMultiSend{ publicstaticvoidMain(){ Socketserver=newSocket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp); IPEndPointiep=new IPEndPoint(IPAddress.Parse("224.100.0.1"),9050); byte[]data=Encoding.ASCII.GetBytes("Thisisatestmessage"); server.SendTo(data,iep); server.Close(); } } NhndliuMulticast classMultiRecv{ publicstaticvoidMain(){ Socketsock=newSocket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); Console.WriteLine("Readytoreceive "); IPEndPointiep=newIPEndPoint(IPAddress.Any,9050); EndPointep=(EndPoint)iep; sock.Bind(iep); sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, newMulticastOption(IPAddress.Parse("224.100.0.1"))); byte[]data=newbyte[1024]; intrecv=sock.ReceiveFrom(data,refep); stringstringData=Encoding.ASCII.GetString(data,0,recv); Console.WriteLine("received:{0}from:{1}",stringData,ep.ToString()); sock.Close(); } } 51
  53. Simpo GidliuMulticastviTTLPDF Merge and Split Unregistered Version - classNewMultiSend{ publicstaticvoidMain(){ Socketserver=newSocket(AddressFamily.InterNetwork, SocketType.Dgram,ProtocolType.Udp); IPEndPointiep=newIPEndPoint(IPAddress.Any,9051); IPEndPointiep2=newIPEndPoint(IPAddress.Parse("224.100.0.1"),9050); server.Bind(iep); byte[]data=Encoding.ASCII.GetBytes("Thisisatestmessage"); server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, newMulticastOption(IPAddress.Parse("224.100.0.1"))); server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,50); server.SendTo(data,iep2); server.Close(); } }  MulticastvilpUdpClient  JoinMulticastGroup()  DropMulticastGroup()  JoinMulticastGroup()làphươngthcoverload  JoinMulticastGroup(IPAddress)  JoinMulticastGroup(IPAddress,int) classUdpClientMultiSend{ publicstaticvoidMain(){ UdpClientsock=newUdpClient(); IPEndPointiep=newIPEndPoint(IPAddress.Parse("224.100.0.1"),9050); byte[]data=Encoding.ASCII.GetBytes("Thisisatestmessage"); sock.Send(data,data.Length,iep); sock.Close(); } } classUdpClientMultiRecv { publicstaticvoidMain() { UdpClientsock=newUdpClient(9050); Console.WriteLine("Readytoreceive "); sock.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"),50); IPEndPointiep=newIPEndPoint(IPAddress.Any,0); byte[]data=sock.Receive(refiep); stringstringData=Encoding.ASCII.GetString(data,0,data.Length); Console.WriteLine("received:{0}from:{1}",stringData,iep.ToString()); sock.Close(); } } 52
  54. Simpo 2.7BàitpápdngPDF Merge and Split Unregistered Version - classMulticastChat:Form{ TextBoxnewText; ListBoxresults; Socketsock; Threadreceiver; IPEndPointmultiep=newIPEndPoint(IPAddress.Parse("224.100.0.1"),9050); publicMulticastChat(){ Text="MulticastChatProgram"; Size=newSize(400,380); Labellabel1=newLabel(); label1.Parent=this; label1.Text="Entertextstring:"; label1.AutoSize=true; label1.Location=newPoint(10,30); newText=newTextBox(); newText.Parent=this; newText.Size=newSize(200,2*Font.Height); newText.Location=newPoint(10,55); results=newListBox(); results.Parent=this; results.Location=newPoint(10,85); results.Size=newSize(360,18*Font.Height); Buttonsendit=newButton(); sendit.Parent=this; sendit.Text="Send"; sendit.Location=newPoint(220,52); sendit.Size=newSize(5*Font.Height,2*Font.Height); sendit.Click+=newEventHandler(ButtonSendOnClick); Buttoncloseit=newButton(); closeit.Parent=this; closeit.Text="Close"; closeit.Location=newPoint(290,52); closeit.Size=newSize(5*Font.Height,2*Font.Height); closeit.Click+=newEventHandler(ButtonCloseOnClick); sock=newSocket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); IPEndPointiep=newIPEndPoint(IPAddress.Any,9050); sock.Bind(iep); sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, 53
  55. Simpo newMulticastOption(IPAddress.ParPDF Merge and Split Unregistered Version - "224.100.0.1"))); receiver=newThread(newThreadStart(packetReceive)); receiver.IsBackground=true; receiver.Start(); } voidButtonSendOnClick(objectobj,EventArgsea){ byte[]message=Encoding.ASCII.GetBytes(newText.Text); newText.Clear(); sock.SendTo(message,SocketFlags.None,multiep); } voidButtonCloseOnClick(objectobj,EventArgsea){ receiver.Abort(); sock.Close(); Close(); } voidpacketReceive(){ EndPointep=(EndPoint)multiep; byte[]data=newbyte[1024]; stringstringData; intrecv; while(true){ recv=sock.ReceiveFrom(data,refep); stringData=Encoding.ASCII.GetString(data,0,recv); results.Items.Add("from"+ep.ToString()+":"+stringData); } } publicstaticvoidMain(){ Application.Run(newMulticastChat()); } } 54
  56. Simpo PDF Merge and Split Unregistered Version - CHƯƠNG3:XÂYDNGNGDNGMNG 3.1.GiaothcICMP GiithiugiaothcICMP(InternetworkControlMessageProtocol) GiaothcICMPhotñngtrênlayer2InternetworktrongmôhìnhTCP/IPhoc layer3NetworktrongmôhìnhOSI ChophépkimtravàxácñnhlicaLayer3InternetworktrongmôhìnhTCP/IP bngcáchñnhnghĩaracácloithôngñipcóthsdngñxácñnhxemmnghin ticóthtruynñưcgóitinhaykhông. Trongthct,ICMPcncácthànhphncamigóitinIPñcóthhotñngñưc. CutrúccagóitinIPvàICMP +Type:cóthlàmtqueryhaymtli +Code:Xácñnhñâylàloiqueryhaythôngñipli +Checksum:KimtravàsalichodliuICMP +Message:TuỳthucvàoTypevàCode 3.1.1.SdngRawSocket GóitinICMPkhôngsdngTCPhocUDPnênchúngtakhôngthsdngcáclp ñưchtrnhưTcpClienthayUdpClientmàphisdngmtRawSocket Mun to Raw Socket khi to ra Socket bn s dng SocketType.Raw, giao thc ICMP ToRawSocketnhưsau Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); RawSocketFormat Value Description Ggp GatewaytoGatewayProtocol Icmp InternetControlMessageProtocol 55
  57. Simpo PDF MergeIdp and Split Unregistered IDPProtocol Version - Igmp InternetGroupManagementProtocol IP ArawIPpacket Ipx NovellIPXProtocol ND NetDiskProtocol Pup XeroxPARCUniversalProtocol(PUP) Raw ArawIPpacket Spx NovellSPXProtocol SpxII NovellSPXVersion2Protocol Unknown Anunknownprotocol Unspecified Anunspecifiedprotocol  GigóidliuRaw  ICMPlàgiaothckhônghưngktni  SdngphươngthcSendTo()calpSocketñgi  CngtronggiaothcICMPkhôngquantrng IPEndPointiep=newIPEndPoint(IPAddress.Parse("192.168.1.2"),0); sock.SendTo(packet,iep);  NhngóidliuRaw  SdngphươngthcReceiveFormcalpSocket  DliunhnvlàmtgóitinIPchúngtaphitáchrañlygóitinICMP RawSocketkhôngtñngñnhdnggóitinICMPchochúngta.Chúngtaphitlàm DataVariable Size Type Type 1byte Byte Code 1byte Byte Checksum 2bytes Unsigned16bitinteger Message multibyte Bytearray ðnhnghĩalpvàphươngthckhitomcñnh classICMP{ publicbyteType; publicbyteCode; publicUInt16Checksum; publicintMessagesize; publicbyte[]Message=newbyte[1024]; publicICMP(){ } }  ToragóitinICMP ICMPpacket=newICMP(); 56
  58. Simpo PDF Merge packet.Type=0x08; and Split Unregistered Version - packet.Code=0x00; packet.Checksum=0; publicICMP(byte[]data,intsize){ Type=data[20]; Code=data[21]; Checksum=BitConverter.ToUInt16(data,22); MessageSize=size24; Buffer.BlockCopy(data,24,Message,0,MessageSize); } publicbyte[]getBytes(){ byte[]data=newbyte[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); returndata; } publicUInt16getChecksum(){ UInt32chcksm=0; byte[]data=getBytes(); intpacketsize=MessageSize+8; intindex=0; while(index >16)+(chcksm&0xffff); chcksm+=(chcksm>>16); return(UInt16)(~chcksm); } 3.1.2.SdnggiaothcICMPvàRawSocketñxâydngchươngtrìnhPing 57
  59. Simpo PDF Merge and Split Unregistered Version - classProgram{ staticvoidMain(string[]args){ byte[]data=newbyte[1024]; intrecv; Sockethost=newSocket(AddressFamily.InterNetwork,SocketType.Raw, ProtocolType.Icmp); IPEndPointiep=newIPEndPoint(IPAddress.Parse(argv[0]),0); EndPointep=(EndPoint)iep; ICMPpacket=newICMP(); 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("testpacket"); Buffer.BlockCopy(data,0,packet.Message,4,data.Length); packet.MessageSize=data.Length+4; intpacketsize=packet.MessageSize+4; UInt16chcksum=packet.getChecksum(); packet.Checksum=chcksum; host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout,3000); host.SendTo(packet.getBytes(),packetsize,SocketFlags.None,iep); try{ data=newbyte[1024]; recv=host.ReceiveFrom(data,refep); }catch(SocketException){ Console.WriteLine("Noresponsefromremotehost"); return; } ICMPresponse=newICMP(data,recv); Console.WriteLine("responsefrom:{0}",ep.ToString()); Console.WriteLine("Type{0}",response.Type); Console.WriteLine("Code:{0}",response.Code); intIdentifier=BitConverter.ToInt16(response.Message,0); 58
  60. Simpo intSequence=BitConverter.ToInt16(responsPDF Merge and Split Unregistered Version - 2); Console.WriteLine("Identifier:{0}",Identifier); Console.WriteLine("Sequence:{0}",Sequence); stringstringData=Encoding.ASCII.GetString(response.Message,4, response.MessageSize4); Console.WriteLine("data:{0}",stringData); host.Close(); } } 3.1.3.SdnggiaothcICMPvàRawSocketñxâydngchươngtrình TraceRoute classTraceRoute{ publicstaticvoidMain(string[]argv){ byte[]data=newbyte[1024]; intrecv,timestart,timestop; Sockethost=newSocket(AddressFamily.InterNetwork, SocketType.Raw,ProtocolType.Icmp); IPHostEntryiphe=Dns.Resolve(argv[0]); IPEndPointiep=newIPEndPoint(iphe.AddressList[0],0); EndPointep=(EndPoint)iep; ICMPpacket=newICMP(); 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("testpacket"); Buffer.BlockCopy(data,0,packet.Message,4,data.Length); packet.MessageSize=data.Length+4; intpacketsize=packet.MessageSize+4; UInt16chcksum=packet.getCchecksum(); packet.Checksum=chcksum; host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout,3000); intbadcount=0; for(inti=1;i<50;i++){ host.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive,i); timestart=Environment.TickCount; host.SendTo(packet.getBytes(),packetsize,SocketFlags.None,iep); try{ data=newbyte[1024]; recv=host.ReceiveFrom(data,refep); timestop=Environment.TickCount; ICMPresponse=newICMP(data,recv); if(response.Type==11) Console.WriteLine("hop{0}:responsefrom{1},{2}ms", i,ep.ToString(),timestoptimestart); if(response.Type==0){ Console.WriteLine("{0}reachedin{1}hops,{2}ms.", ep.ToString(),i,timestoptimestart); break; 59
  61. Simpo }PDF Merge and Split Unregistered Version - badcount=0; }catch(SocketException){ Console.WriteLine("hop{0}:Noresponsefromremotehost",i); badcount++; if(badcount==5){ Console.WriteLine("Unabletocontactremotehost"); break; } } } host.Close(); } } 3.2.GiaothcSMTP,POP3 3.2.1.CơbnvhthngMailvàgiaothcSMTP,POP3 60
  62. Simpo PDF Merge and Split Unregistered Version - *GiaothcSMTP MtslnhcơbncagiaothcSMTP: Lnh Môt HELO Hello.Sdngñxácñnhngưigiñin.Lnhnàynàyñi kèmvitêncahostgiñin.TrongESTMP(extended protocol),thìlnhnàyslàEHLO. MAIL Khitomtgiaodchgithư.Nókthp"from"ñxácñnh ngưigithư. RCPT Xácñnhngưinhnthư. DATA Thôngbáobtñunidungthcscabcñin(phnthân cathư).Dliuñưcmãthànhdngmã128bitASCIIvànó ñưcktthúcvimtdòngñơnchaduchm(.). RSET Hubgiaodchthư VRFY Sdngñxácthcngưinhnthư. NOOP Nólàlnh"nooperation"xácñnhkhôngthchinhành ñnggì QUIT Thoátkhitintrìnhñktthúc SEND Chohostnhnbitrngthưcònphigiñnñucuikhác. MtslnhkhôngyêucuphicóñưcxácñnhbngRFC821 SOML Sendormail.Báovihostnhnthưrngthưphi giñnñucuikháchochpthư. SAML Sendandmail.Nóivihostnhnrngbcñin phigitingưidùngñucuivàhpthư. EXPN Sdngmrngchomtmailinglist. HELP Yêucuthôngtingiúpñtñunhnthư. TURN Yêucuñhostnhngivaitròlàhostgithư. MãtrngtháicaSMTP KhimtMTAgimtlnhSMTPtiMTAnhnthìMTAnhnstrlivi mtmãtrngtháiñchongưigibitñangcóvicgìxyrañunhn.Vàdưiñây làbngmãtrngtháicaSMTPtheotiêuchunRFC821.Mcñcatrngtháiñưc 61
  63. Simpo xácñnhbisñutiêncamã(5xxlàlinng,4PDF Merge and Split Unregistered Version - làlitmthi,1xx–3xxlàhot ñngbìnhthưng). MtsmãtrngtháicaSMTP 211Tìnhtrnghthng,hayreplygiúpñhthng 214Thôngñipgiúpñ. 220 dchvsnsàng 221 dchvñóngkênhgiaochuyn 250HànhñngmailyêucuOK,hoànthành 251Userkhôngccb;shưngñn 354Khiñngvicnhpmail;ktthúcvi . 421 dchvkhôngsdngñưc,ñóngkênhgiaochuyn 450Khônglyhànhñngmailyêucu;mailboxkhônghiulc 451Khôngnhnhànhñngñưcyêucu;lưutrcahthng khôngñ. 500Licúpháp;khôngchpnhnlnh 501Licúpháptrongthamshayñis 502 Lnhkhôngñưccungcp 503 Dònglnhsai 504Thamscadònglnhkhôngñưccungcp 550Khôngnhnhànhñngñưcyêucu;mailboxkhônghiulc [nhưmailboxkhôngtìmthyhaykhôngtruycpñưc] 551Userkhôngccb;vuilòngth 552Bquahànhñngmàmailyêucu,vưtquáchñnhlưutr 554Khôngnhnhànhñngñưcyêucu;tênmailboxkhôngñưc chpnhn.[nhưsaicúphápmailbox]giaochuynsai. ðnhdngcamtbcthưthôngthưngkhôngcóphnñínhkèmnhưsau: *GiaothcPOP3 Giaothcdùngñlythư,POP3Serverlngnghetrêncng110,môttrong RFC1939 62
  64. Simpo MtslnhcaPOP3PDF Merge and Split Unregistered Version - USERXácñnhusername PASS Xácñnhpassword STATYêucuvtrngtháicahpthưnhưslưngthưvàñlncathư LIST Hindanhsáchcathư RETRNhnthư DELEXoámtbcthưxácñnh NOOPKhônglàmgìc RSETKhôiphclinhưthưñãxoá(rollback) QUITThchinvicthayñivàthoátra 3.2.2.CàiñtSMTP,POP3Client/Server VitchươngtrìnhgiMailñơngintheogiaothcSMTP usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.IO; classProgram{ staticvoidMain(string[]args){ stringnguoigui,nguoinhan,tieude,body; stringdiachimaychu; intportmaychu; Console.Write("NhapdichuSMTPServer:"); diachimaychu=Console.ReadLine(); Console.Write("Nhapcongcuamaychu:"); portmaychu=int.Parse(Console.ReadLine()); Console.Write("Nhapdiachinguoigui:"); nguoigui=Console.ReadLine(); Console.Write("Nhapdiachinguoinhan:"); nguoinhan=Console.ReadLine(); Console.Write("Nhaptieudebucthu:"); tieude=Console.ReadLine(); Console.Write("Nhapnoidungbucthu:"); body=Console.ReadLine(); //TaoEndpoitcuamaychu IPEndPointiep=newIPEndPoint(IPAddress.Parse(diachimaychu),portmaychu); TcpClientclient=newTcpClient(); client.Connect(iep); stringData="Helo"; StreamReadersr=newStreamReader(client.GetStream()); StreamWritersw=newStreamWriter(client.GetStream()); sw.WriteLine(Data); sw.Flush(); //DocthongbaotuServerguivevaxulyneucanthiet Console.WriteLine(sr.ReadLine()); 63
  65. Simpo //GuidiachinguyoiguiPDF Merge and Split Unregistered Version - Data="MAILFROM: "; sw.WriteLine(Data); sw.Flush(); //DocthongbaotuServerguivevaxulyneucanthiet Console.WriteLine(sr.ReadLine()); //Guidiachinguyoigui Data="RCPTTO: "; sw.WriteLine(Data); sw.Flush(); //DocthongbaotuServerguivevaxulyneucanthiet Console.WriteLine(sr.ReadLine()); //Batdauguinoidungbucthu Data="Data"; sw.WriteLine(Data); sw.Flush(); //DocthongbaotuServerguivevaxulyneucanthiet Console.WriteLine(sr.ReadLine()); //Guinoidungbucthu Data="SUBJECT:"+tieude+"\r\n"+body+"\r\n"+"."+"\r\n"; sw.WriteLine(Data); sw.Flush(); //DocthongbaotuServerguivevaxulyneucanthiet Console.WriteLine(sr.ReadLine()); //Ngatketnoi Data="QUIT"; sw.WriteLine(Data); sw.Flush(); //DocthongbaotuServerguivevaxulyneucanthiet Console.WriteLine(sr.ReadLine()); sr.Close(); sw.Close(); client.Close(); Console.ReadLine(); } } 64
  66. Simpo VitchươngtrìnhlythưñơngintheogiaothcPOP3PDF Merge and Split Unregistered Version - usingSystem; usingSystem.Collections.Generic; usingSystem.Data; usingSystem.Drawing; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.Threading; usingSystem.IO; usingSystem.Net; usingSystem.Net.Sockets; namespaceMyPop3{ publicpartialclassForm1:Form{ TcpClientpopclient; StreamReadersr; StreamWritersw; publicForm1(){ InitializeComponent(); CheckForIllegalCrossThreadCalls=false; 65
  67. Simpo }PDF Merge and Split Unregistered Version - privatevoidbtLogin_Click(objectsender,EventArgse){ IPEndPointiep=newIPEndPoint(IPAddress.Parse(txtPOP.Text), int.Parse(txtPort.Text)); popclient=newTcpClient(); popclient.Connect(iep); sr=newStreamReader(popclient.GetStream()); sw=newStreamWriter(popclient.GetStream()); sr.ReadLine(); stringdata=""; 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(); strings=sr.ReadLine(); char[]ch={''}; string[]tam=s.Split(ch); //MessageBox.Show("sobucthula:"+tam[1]); while((s=sr.ReadLine())!="."){ lstHeader.Items.Add(s); } } privatevoidlstHeader_SelectedIndexChanged(objectsender,EventArgse){ inti=lstHeader.SelectedIndex+1; //Laybucthuvevatienhanhphantich stringdata="RETR"+i.ToString(); sw.WriteLine(data); sw.Flush(); strings; //MessageBox.Show(sr.ReadLine()); //Layphanheader while((s=sr.ReadLine().Trim())!=null){ //MessageBox.Show(s); if(s.Length==0)break; if(s.ToUpper().StartsWith("DATE")){ DateTimedt=DateTime.Parse(s.Substring(5,s.Length5)); txtDate.Text=dt.ToShortDateString()+""+dt.ToLongTimeString(); } if(s.ToUpper().StartsWith("FROM")) 66