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

SinhVienIT.Net---LapTrinhMangV1.0

Embed Size (px)

Citation preview

  • 1

    CHNG 1: CC KIN THC C BN V MNG MY TNH.......................................3 1.1. M hnh tham kho 7 tng OSI........................................................................................3 1.2. H giao thc TCP/IP........................................................................................................5 1.3. So snh gia hai giao thc TCP v UDP.........................................................................6 1.4. Cng giao thc.................................................................................................................7 1.5. a ch IP, cc a ch IP dnh ring................................................................................7 1.6. a ch tn min: loi A, loi MX.. .................................................................................8 1.7. Mt s giao thc tng ng dng: HTTP, SMTP, POP3, FTP... ...................................8

    CHNG 2: LP TRNH MNG TRONG .NET FRAMEWORK ........................................9 2.1. Socket hng kt ni (TCP Socket) ................................................................................9 2.1.1. Gii thiu v NameSpace System.Net v System.Net.Sockets ..............................10 2.1.2. Vit chng trnh cho pha my ch.......................................................................11 2.1.3. Vit chng trnh cho pha my khch...................................................................13 2.1.4. S dng cc lung nhp xut vi Socket................................................................14

    2.2. Socket khng hng kt ni (UDP Socket)...................................................................17 2.2.1. Vit chng trnh cho pha my ch.......................................................................17 2.2.2. Vit chng trnh cho pha my khch...................................................................18 2.2.3. S dng lp System.IO.MemoryStream to vng m nhp xut.....................20

    2.3. S dng cc lp h tr c xy dng t lp Soket .....................................................20 2.3.1. Lp TCPClient........................................................................................................21 2.3.2. Lp TCPListener ....................................................................................................22 2.3.3. Lp UDPClient .......................................................................................................24

    2.4. Socket khng ng b....................................................................................................26 2.4.1. M hnh x l s kin ca windows.......................................................................26 2.4.2. S dng Socket khng ng b ..............................................................................27 2.4.3. V d v Socket khng ng b..............................................................................28 2.4.4. S dng cc phng thc Non-blocking ................................................................35

    2.5. S dng Thread trong cc ng dng mng....................................................................39 2.5.1. S dng Thread trong chng trnh .Net ................................................................40 2.5.2. S dng Thread trong cc chng trnh Server ......................................................41 2.5.3. S dng Thread gi/nhn d liu.......................................................................41 2.5.4. S dng ThreadPool trong cc chng trnh .Net ..................................................43 2.5.5. S dng ThreadPool trong cc chng trnh Server...............................................47

    2.6. K thut IP Multicasting................................................................................................48 2.6.1. Broadcasting l g?..................................................................................................48 2.6.2. S dng Broadcasting gi d liu n nhiu my trong mng cc b ..............48 2.6.3. Multicasting l g? ..................................................................................................49 2.6.4. Socket Multicasting trong .Net ...............................................................................50

    2.7 Bi tp p dng ...............................................................................................................53 CHNG 3: XY DNG NG DNG MNG...................................................................55 3.1. Giao thc ICMP.............................................................................................................55 3.1.1. S dng Raw Socket...............................................................................................55 3.1.2. S dng giao thc ICMP v Raw Socket xy dng chng trnh Ping.............57 3.1.3. S dng giao thc ICMP v Raw Socket xy dng chng trnh TraceRoute .58

    3.2. Giao thc SMTP, POP3.................................................................................................60 3.2.1. C bn v h thng Mail v giao thc SMTP, POP3 .............................................60 3.2.2. Ci t SMTP, POP3 Client/Server ........................................................................60

    3.3. Giao thc HTTP.............................................................................................................67 3.3.1. C bn v giao thc HTTP .....................................................................................67 3.3.2. Ci t HTTP Client/Server....................................................................................68

    3.4. Giao thc FTP................................................................................................................74 3.4.1. C bn v giao thc FTP ........................................................................................74 3.4.2. Ci t FTP Client/Server.......................................................................................84

  • 2

    3.5. DNS (Domain Name Server) .........................................................................................88 3.5.1. Vn phn gii tn min ......................................................................................88 3.5.2. Trin khai DNS MX (Mail Exchange) ...................................................................89

    3.6 Tho lun v cc ng dng khc thng gp .................................................................93 3.7 Bi tp p dng ...............................................................................................................93

    CHNG 4: XY DNG NG DNG NHIU LP ..........................................................94 4.1. M hnh 2 lp (two tier), 3 lp (three tier) v n lp. .....................................................94 4.2. Remoting........................................................................................................................98 4.2.1. Gii thiu v Remoting.........................................................................................102 4.2.2. Khai bo, ci t v ng k giao din t xa ........................................................102 4.2.3. Triu gi phng thc t xa .................................................................................107

    4.3. Web Serive...................................................................................................................107 4.3.1. Gii thiu v Web Serives ....................................................................................107 4.3.2. Giao thc SOAP ...................................................................................................109 4.3.3. Xy dng Web Services........................................................................................112 4.3.4. Triu gi Web Services t ng dng .NET, Java v cc ngn ng khc .............114

    4.4 Tho lun v cc ng dng phn tn ............................................................................116 4.5. Bi tp p dng ............................................................................................................116

  • 3

    CHNG 1: CC KIN THC C BN V MNG MY TNH 1.1. M hnh tham kho 7 tng OSI

    M hnh kt ni h thng m c T chc quc t v tiu chun ho ISO (International Organizaiton for Standardization) a ra nhm cung cp mt m hnh

    chun cho cc nh sn xut v cung cp sn phm vin thng p dng theo pht trin cc sn phm vin thng. tng m hnh ho c to ra cn nhm h tr cho

    vic kt ni gia cc h thng v modun ho cc thnh phn phc v mng vin thng.

    a. Chc nng ca m hnh OSI: - Cung cp kin thc v hot ng ca kt ni lin mng

    - a ra trnh t cng vic thit lp v thc hin mt giao thc cho kt ni cc thit b trn mng.

    M hnh OSI cn c mt s thun li sau : - Chia nh cc hot ng phc tp ca mng thnh cc phn cng vic n gin.

    - Cho php cc nh thit k c kh nng pht trin trn tng modun chc nng. - Cung cp cc kh nng nh ngha cc chun giao tip c tnh tng thch cao

    plug and play v tch hp nhiu nh cung cp sn phm.

    b. Cu trc m hnh OSI: M hnh OSI gm 7 lp (level), mi lp thc hin cc chc nng ring cho hot ng kt ni mng.

    Hnh 1-1 M t by lp OSI. 4 lp u nh ngha cch thc cho u cui thit lp kt ni vi nhau trao i d liu. 3 lp trn dng pht trin cc ng dng u

    cui kt ni vi nhau v ngi dng.

    Aplication

    Presentation

    Application

    (Upper Layer) Session

    Transport Layer

    Network Layer

    Data Link

    Physical

    Data Lower Layer

    Cc lp trn 3 lp trn cng ca m hnh OSI thng c gi l cc lp ng dng (Application layers) hay cn gi l cc lp cao. Cc lp ny thng lin quan ti giao tip vi

    ngi dng, nh dng ca d liu v phng thc truy nhp cc ng dng . Hnh 1-2 M t cc lp trn v cung cp thng tin vi cc chc nng ca n qua v

    d:

    - Lp ng dng: chc nng giao Telnet, HTTP

  • 4

    Application

    tip gia ngi s dng v cc chng trnh ng dng

    Presentation

    - Lp trnh by: cch thc chun ho d liu v trnh by s liu

    - C chc nng c bit l m ho d liu ngi s dung

    ASSCII

    EBCDIC

    JPEC

    Session

    - Lp phin: thit lp, duy tr v hu b mt phin lm vic

    NFS, SQL

    Transport Layer

    Network Layer

    Data Link

    Physical

    - Application layer : y l lp cao nht trong m hnh. N l ni m ngi s

    dng hoc kt ni cc chng trnh ng dng vi cc th tc cho php truy nhp vo mng.

    - Presentation layer : Lp presentation cung cp cc m v chc nng chuyn i m c cung cp bi lp ng dng. Cc chc nng m bo rng d liu t

    lp ng dng trong mt h thng c th c c bi lp ng dng ca mt h thng khc. VD : dng m ho d liu t lp ng dng : nh m ho nh jpeg , gif. M

    cho php ta c th hin ln trang web . - Session layer : c s dng thit lp, duy tr v kt thc phin lm vic

    gia cc lp presentation. Vic trao i thng tin lp ny bao gm yu cu dch v v p ng yu cu ca cc ng dng trn thit b khc.

    Cc lp di. 4 lp di ca m hnh OSI s dng nh ngha lm th no d liu c

    truyn i trong cc dy ni vt l, cc thit b mng v i n trm u cui cui cng l n cc lp ng dng. Qun sch ny ta ch quan tm n 4 lp cui. V s xem xt

    tng lp mt cch chi tit giao thip gia cc lp trong m hnh OSI: S dng phng php protocal stack kt ni gia hai thit b trong mng. Protocal

    stack l mt tp hp cc quy nh dng nh ngha lm th no d liu truyn qua mng.

    V d vi : TCP/IP mi Layer cho php d liu truyn qua. Cc lp trao i cc thng tin cung cp cuc lin lc gia hai thit b trong mng. Cc lp giao tip vi

    nhau s dng Protocal Data Unit (PDU). Thng tin iu khin ca PDU c thm

  • 5

    vo vi d liu lp trn. V thng tin iu khin ny nm trong trng gi l trng header v trailer.

    Hnh 1-3 Data encapsulation

    Application

    Presentation

    Upper Layer Data Session

    TCP Header Upper Layer Data Transport Segment

    IP Header Data Network Packet

    LLC Header Data FCS Data Link Frame

    MAC Header Data FCS Physical Bits

    0101110101001000010

    1.2. H giao thc TCP/IP

    Cc tng ca giao thc TCP/IP so vi cc tng ca m hnh OSI

    Application: Xc nhn quyn, nn d liu v cc dch v cho ngi dng Transport: X l d liu gia cc h thng va cung cp vic truy cp mng cho cc ng dng

    Network: Tm ng cho cc packet

  • 6

    Link: Mc OS hoc cc thit b giao tip mng trn mt my tnh

    Mt s im khc nhau ca TCP/IP v m hnh OSI + Lp ng dng trong TCP/IP x l chc nng ca lp 5,6,7 trong m hnh OSI + Lp transport trong TCP/IP cung cp c ch UDP truyn khng tin cy, transport

    trong OSI lun m bo truyn tin cy + TCP/IP l mt tp ca cc protocols (mt b giao thc) + TCP/IP xy dng trc OSI

    Quy trnh ng gi d liu trong m hnh TCP/IP nh sau:

    1.3. So snh gia hai giao thc TCP v UDP

  • 7

    1.4. Cng giao thc

    L mt s nm trong khong 1..65535 dng phn bit gia 2 ng dng mng vi nhau gn vi a ch IP v Socket

    Mt s cng v cc giao thc thng dng:

    + FTP: 21 + Telnet: 23 + SMTP: 25 + POP3: 110 + HTTP:80 1.5. a ch IP, cc a ch IP dnh ring

    Reverved for future use01111Class E

    Multicast address0111Class D

    HostidNetid011Class C

    HostidNetid01Class B

    HostidNetid0Class A

    2416843210

    Reverved for future use01111Class E

    Multicast address0111Class D

    HostidNetid011Class C

    HostidNetid01Class B

    HostidNetid0Class A

    2416843210

  • 8

    1.6. a ch tn min: loi A, loi MX..

    1.7. Mt s giao thc tng ng dng: HTTP, SMTP, POP3, FTP...

    - Chng ta s nghin cu chi tit cc giao thc ny chng 3

  • 9

    CHNG 2: LP TRNH MNG TRONG .NET FRAMEWORK 2.1. Socket hng kt ni (TCP Socket)

    Socket l mt giao din lp trnh ng dng (API) mng

    Thng qua giao din ny chng ta c th lp trnh iu khin vic truyn thng gia

    hai my s dng cc giao thc mc thp l TCP, UDP

    Socket l s tru tng ho mc cao, c th tng tng n nh l thit b truyn

    thng hai chiu gi nhn d liu gia hai my tnh vi nhau.

    Cc loi Socket

    Socket hng kt ni (TCP Socket)

    Socket khng hng kt ni (UDP Socket)

    Raw Socket

    c im ca Socket hng kt ni

    C 1 ng kt ni o gia 2 tin trnh

    Mt trong 2 tin trnh phi i tin trnh kia yu cu kt ni.

    C th s dng lin lc theo m hnh Client/Server

    Trong m hnh Client/Server th Server lng nghe v chp nhn mt yu

    cu kt ni

    Mi thng ip gi u c xc nhn tr v

    Cc gi tin chuyn i tun t

    c im ca Socket khng hng kt ni Hai tin trnh lin lc vi nhau khng kt ni trc tip Thng ip gi i phi km theo a ch ca ngi nhn Thng ip c th gi nhiu ln Ngi gi khng chc chn thng ip ti tay ngi nhn Thng ip gi sau c th n ch trc thng ip gi trc .

    S hiu cng ca Socket

  • 10

    c th thc hin cc cuc giao tip, mt trong hai qu trnh phi cng

    b s hiu cng ca socket m mnh s dng.

    Mi cng giao tip th hin mt a ch xc nh trong h thng. Khi qu

    trnh c gn mt s hiu cng, n c th nhn d liu gi n cng

    ny t cc qu trnh khc.

    Qu trnh cn li cng yu cu to ra mt socket.

    2.1.1. Gii thiu v NameSpace System.Net v System.Net.Sockets Cung cp mt giao din lp trnh n gin cho rt nhiu cc giao thc mng. C rt nhiu lp lp trnh

    Ta quan tm lp IPAdress, IPEndPoint, DNS, Lp IPAdress

    Mt s Field cn ch : Any: Cung cp mt a ch IP ch ra rng Server phi lng nghe trn

    tt c cc Card mng Broadcast: Cung cp mt a ch IP qung b

    Loopback: Tr v mt a ch IP lp AdressFamily: Tr v h a ch ca IP hin hnh

    Lp IPAddress Mt s phng thc cn ch :

    Phng thc khi to IPAddress(Byte[])

    IPAddress(Int64) IsLoopback: Cho bit a ch c phi a ch lp khng

    Parse: Chuyn IP dng xu v IP chun ToString: Tr a ch IP v dng xu

    TryParse: Kim tra IP dng xu c hp l khng? Lp IPEndPoint

    Mt s phng thc cn ch : Phng thc khi to

    IPEndPoint (Int64, Int32) IPEndPoint (IPAddress, Int32)

    Create: To mt EndPoint t mt a ch Socket ToString : Tr v a ch IP v s hiu cng theo khun dng aCh:

    Cng, v d: 192.168.1.1:8080 Lp DNS

    Mt s thnh phn ca lp: HostName: Cho bit tn ca my c phn gii

    GetHostAddress: Tr v tt c IP ca mt trm GetHostEntry: Gii p tn hoc a ch truyn vo v tr v i tng

    IPHostEntry

  • 11

    GetHostName: Ly v tn ca my tnh cc b NameSpace System.Net.Sockets

    Mt s lp hay dng: TcpClient, UdpClient, TcpListener, Socket, NetworkStream,

    to ra Socket Socket(AddressFamily af, SocketType st, ProtocolType pt)

    SocketType Protocoltype Description

    Dgram Udp Connectionless communication

    Stream Tcp Connection-oriented communication

    Raw Icmp Internet Control Message Protocol

    Raw Raw Plain IP packet communication

    using System.Net; using System.Net.Sockets; class SockProp { public static void Main() { IPAddress ia = IPAddress.Parse("127.0.0.1"); IPEndPoint ie = new IPEndPoint(ia, 8000); Socket test = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Console.WriteLine("AddressFamily: {0}", test.AddressFamily); Console.WriteLine("SocketType: {0}", test.SocketType); Console.WriteLine("ProtocolType: {0}", test.ProtocolType); Console.WriteLine("Blocking: {0}", test.Blocking); test.Blocking = false; Console.WriteLine("new Blocking: {0}", test.Blocking); Console.WriteLine("Connected: {0}", test.Connected); test.Bind(ie); IPEndPoint iep = (IPEndPoint)test.LocalEndPoint; Console.WriteLine("Local EndPoint: {0}", iep.ToString()); test.Close(); Console.ReadKey(); } } 2.1.2. Vit chng trnh cho pha my ch

    Vit chng trnh cho pha my ch To mt Socket

    Lin kt vi mt IPEndPoint cc b Lng nghe kt ni

    Chp nhn kt ni Gi nhn d liu theo giao thc thit k

  • 12

    ng kt ni sau khi hon thnh v tr li trng thi lng nghe ch kt ni mi

    Vit chng trnh cho pha my ch IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);

    Socket newsock = Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    newsock.Bind(ipep); newsock.Listen(10);

    Socket client = newsock.Accept(); //Gi nhn d liu theo giao thc thit k

    . newsock.Close(); Chng trnh Server: using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; class Server{ static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Bind(iep); server.Listen(10); Console.WriteLine("Cho ket noi tu client"); Socket client = server.Accept(); Console.WriteLine("Chap nhan ket noi tu:{0}", client.RemoteEndPoint.ToString()); string s = "Chao ban den voi Server"; //Chuyen chuoi s thanh mang byte byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes(s); //gui nhan du lieu theo giao thuc da thiet ke client.Send(data,data.Length,SocketFlags.None); while (true) { data = new byte[1024]; int recv = client.Receive(data); if (recv == 0) break; //Chuyen mang byte Data thanh chuoi va in ra man hinh s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("Clien gui len:{0}", s); //Neu chuoi nhan duoc la Quit thi thoat if (s.ToUpper().Equals("QUIT")) break; //Gui tra lai cho client chuoi s s = s.ToUpper(); data = new byte[1024];

  • 13

    data = Encoding.ASCII.GetBytes(s); client.Send(data, data.Length, SocketFlags.None); } client.Shutdown(SocketShutdown.Both); client.Close(); server.Close(); } } 2.1.3. Vit chng trnh cho pha my khch

    Vit chng trnh cho pha my khch

    Xc nh a ch ca Server To Socket

    Kt ni n Server Gi nhn d liu theo giao thc thit k

    ng Socket Vit chng trnh cho pha my khch

    IPEndPoint ipep = new IPEndPoint(Ipaddress.Parse("192.168.1.6"), 9050); Socket server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,

    ProtocolType.Tcp); server.Connect(ipep); Chng trnh Client: using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; class Client { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(iep); byte[] data = new byte[1024]; int recv = client.Receive(data); string s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("Server gui:{0}", s); string input; while (true) { input = Console.ReadLine(); //Chuyen input thanh mang byte gui len cho server data = new byte[1024]; data = Encoding.ASCII.GetBytes(input); client.Send(data, data.Length, SocketFlags.None); if (input.ToUpper().Equals("QUIT")) break; data = new byte[1024]; recv = client.Receive(data);

  • 14

    s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("Server gui:{0}", s); } client.Disconnect(true); client.Close(); } }

    2.1.4. S dng cc lung nhp xut vi Socket T Socket ta c th to ra lung nhp xut vi Socket l s dng lp NetworkStream

    Property Description

    CanRead Is true if the NetworkStream supports reading

    CanSeek Is always false for NetworkStreams

    CanWrite Is true if the NetworkStream supports writing

    DataAvailable Is true if there is data available to be read

    V d chng trnh Client/Server s dng NetworkStream gi v nhn d liu Chng trnh Client s dng NetworkStream: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets;

  • 15

    class Program { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2009); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(iep); NetworkStream ns = new NetworkStream(client); byte[] data = new byte[1024]; while (true) { string input = Console.ReadLine(); data = Encoding.ASCII.GetBytes(input); ns.Write(data, 0, data.Length); if (input.ToUpper().Equals("QUIT")) break; data = new byte[1024]; int rec = ns.Read(data, 0, data.Length); string s = Encoding.ASCII.GetString(data, 0, rec); Console.WriteLine(s); } client.Close(); } } Chng trnh Server s dng NetworkStream: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; class Program { static void Main(string[] args) { IPEndPoint iep=new IPEndPoint(IPAddress.Parse("127.0.0.1"),2009); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); server.Bind(iep); server.Listen(10); Socket client = server.Accept(); byte[] data; NetworkStream ns = new NetworkStream(client); while (true) { data = new byte[1024]; int rec = ns.Read(data, 0, data.Length); string s = Encoding.ASCII.GetString(data, 0, rec); Console.WriteLine(s); data = new byte[1024]; s = s.ToUpper(); if (s.Equals("QUIT")) break; data = Encoding.ASCII.GetBytes(s); ns.Write(data, 0, data.Length); }

  • 16

    client.Close(); server.Close(); } } Trn c s ca NetworkStream ta c th ni thm cc lung nhp xut theo hng k t nh StreamReader, StreamWriter Sau y l mt v d v chng trnh Client/Server s dng lung nhp xut, chng trnh Server chp php Client gi ln yu cu, nu yu cu l GetDate khng phn bit ch hoa ch thng th Server tr v cho Client ngy hin ti, nu yu cu l GetTime khng phan bit hoa thng th Server tr v gi hin ti, nu l Quit th Server ngt kt ni vi Client, khng phi cc trng hp trn th thng bo khng hiu lnh. Chng trnh pha Client: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; class DateTimeClient { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,

    ProtocolType.Tcp); client.Connect(iep); NetworkStream ns = new NetworkStream(client); StreamReader sr = new StreamReader(ns); StreamWriter sw = new StreamWriter(ns); while (true) { string input = Console.ReadLine(); sw.WriteLine(input); sw.Flush(); if (input.ToUpper().Equals("QUIT")) break; string kq = sr.ReadLine(); Console.WriteLine(kq); } sr.Close(); sw.Close(); ns.Close(); client.Close(); } } Chng trnh pha Server: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net;

  • 17

    using System.Net.Sockets; using System.IO; class DateTimeServer{ static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2009); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,

    ProtocolType.Tcp); server.Bind(iep); server.Listen(10); Socket client = server.Accept(); NetworkStream ns = new NetworkStream(client); StreamReader sr = new StreamReader(ns StreamWriter sw = new StreamWriter(ns); string kq=""; while (true) { string s = sr.ReadLine(); s=s.ToUpper(); if (s.Equals("QUIT")) break; if (s.Equals("GETDATE")) kq = DateTime.Now.ToString("dd/MM/yyyy"); else if (s.Equals("GETTIME")) kq = DateTime.Now.ToString("hh:mm:ss"); else kq = "Khong hieu lenh"; sw.WriteLine(kq); sw.Flush(); } sr.Close(); sw.Close(); client.Close(); } } 2.2. Socket khng hng kt ni (UDP Socket)

    Chng trnh pha my ch To mt Socket

    Lin kt vi mt IPEndPoint cc b Gi nhn d liu theo giao thc thit k

    ng Socket Chng trnh pha my khch

    Xc nh a ch Server To Socket

    Gi nhn d liu theo giao thc thit k ng Socket

    2.2.1. Vit chng trnh cho pha my ch using System;

  • 18

    using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; class Program { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008); Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); server.Bind(iep); //tao ra mot Endpot tu xa de nhan du lieu ve IPEndPoint RemoteEp = new IPEndPoint(IPAddress.Any, 0); EndPoint remote=(EndPoint)RemoteEp; byte[] data = new byte[1024]; int recv = server.ReceiveFrom(data, ref remote); string s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("nhan ve tu Client:{0}", s); data = Encoding.ASCII.GetBytes("Chao client"); server.SendTo(data, remote); while (true) { data=new byte[1024]; recv = server.ReceiveFrom(data, ref remote); s = Encoding.ASCII.GetString(data, 0, recv); if (s.ToUpper().Equals("QUIT")) break; Console.WriteLine(s); data=new byte[1024]; data=Encoding.ASCII.GetBytes(s); server.SendTo(data,0,data.Length,SocketFlags.None,remote); } server.Close(); } } 2.2.2. Vit chng trnh cho pha my khch using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; class Program { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2008); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); String s = "Chao server"; byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes(s); client.SendTo(data, iep); EndPoint remote = (EndPoint)iep;

  • 19

    data = new byte[1024]; int recv = client.ReceiveFrom(data, ref remote); s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("Nhan ve tu Server{0}",s); while (true) { s = Console.ReadLine(); data=new byte[1024]; data = Encoding.ASCII.GetBytes(s); client.SendTo(data, remote); if (s.ToUpper().Equals("QUIT")) break; data = new byte[1024]; recv = client.ReceiveFrom(data, ref remote); s = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine(s); } client.Close(); } }

    S dng Socket khng hng kt ni vit chng trnh chat gia 2 my nh

    sau: (Sau ny chng ta c th s dng lp UdpClient) using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; public partial class Form1 : Form { private Socket udp1; private IPEndPoint ipremote, iplocal; public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void btStart_Click(object sender, EventArgs e) { udp1 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); iplocal = new IPEndPoint(IPAddress.Parse("127.0.0.1"), int.Parse(txtLocalPort.Text)); udp1.Bind(iplocal); ipremote = new IPEndPoint(IPAddress.Parse(txtIp.Text), int.Parse(txtRemotePort.Text)); Thread tuyen = new Thread(new ThreadStart(NhanDL)); tuyen.Start();

  • 20

    } private void btSend_Click(object sender, EventArgs e) { byte[] data = new byte[1024]; data = Encoding.ASCII.GetBytes(txtSend.Text); udp1.SendTo(data, ipremote); } private void NhanDL() { while (true) { byte[] data = new byte[1024]; IPEndPoint ipe = new IPEndPoint(IPAddress.Any, 0); EndPoint remote = (EndPoint)ipe; int rec = udp1.ReceiveFrom(data, ref remote); string s = Encoding.ASCII.GetString(data, 0, rec); txtNoidung.Text += s + "\r\n"; } } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(txtSend.Text.Substring(0, txtSend.Text.IndexOf(" "))); } }

    2.2.3. S dng lp System.IO.MemoryStream to vng m nhp xut 2.3. S dng cc lp h tr c xy dng t lp Soket

  • 21

    2.3.1. Lp TCPClient Mc ch ca lp UDPClient trn l dng cho lp trnh vi giao thc UDP,

    vi giao thc ny th hai bn khng cn phi thit lp kt ni trc khi gi do vy mc tin cy khng cao. m bo tin cy trong cc ng dng mng, ngi ta cn

    dng mt giao thc khc, gi l giao thc c kt ni : TCP (Transport Control Protocol). Trn Internet ch yu l dng loi giao thc ny, v d nh Telnet, HTTP,

    SMTP, POP3 lp trnh theo giao thc TCP, MS.NET cung cp hai lp c tn l TCPClient v TCPListener.

    - Cc thnh phn ca lp TcpClient + Phng thc khi to:

    Constructor Method

    Name Description

    TcpClient () To mt i tng TcpClient. Cha t thng s g.

    TcpClient (IPEndPoint)

    To mt TcpClient v gn cho n mt EndPoint cc b.

    (Gn a ch my cc b v s hiu cng s dng trao i thng tin v sau)

    TcpClient (RemoteHost: String, Int32)

    To mt i tng TcpClient v kt ni n mt my c a ch v s hiu cng c truyn vo.. RemoteHost c th l a ch IP chun hoc tn my.

    + Mt s thuc tnh:

    Name Description

    Available Cho bit s byte nhn v t mng v c sn c.

    Client Tr v Socket ng vi TCPClient hin hnh.

    Connected Trng thi cho bit kt ni c n Server hay cha ?

    + Mt s phng thc:

    Name Description

    Close Gii phng i tng TcpClient nhng khng ng kt ni.

    Connect (RemoteHost, Port)

    Kt ni n mt my TCP khc c Tn v s hiu cng.

  • 22

    GetStream Tr v NetworkStream t gip ta gi hay nhn d liu. (Thng lm tham s khi to StreamReader v StreamWriter) . Khi gn vo StreamReader v StreamWriter ri th ta c th gi v nhn d liu thng qua cc phng thc Readln, writeline tng ng ca cc lp ny.

    Ta s dng lp TcpClient vit li chng trnh DateTimeClient nh sau: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; using System.Threading; class DateTimeClient { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9999); TcpClient client = new TcpClient(); client.Connect(iep); StreamReader sr = new StreamReader(client.GetStream()); StreamWriter sw = new StreamWriter(client.GetStream()); while (true) { string input = Console.ReadLine(); sw.WriteLine(input); sw.Flush(); if (input.ToUpper().Equals("QUIT")) break; string kq = sr.ReadLine(); Console.WriteLine(kq); } sr.Close(); sw.Close(); client.Close(); } } 2.3.2. Lp TCPListener

    TCPListerner l mt lp cho php ngi lp trnh c th xy dng cc ng

    dng Server (V d nh SMTP Server, FTP Server, DNS Server, POP3 Server hay server t nh ngha .). ng dng server khc vi ng dng Client ch n lun

    lun thc hin lng nghe v chp nhn cc kt ni n t Client.

  • 23

    Cc thnh phn ca lp TcpListener: + Phng thc khi to:

    Constructor method

    Name Description

    TcpListener (Port: Int32)

    To mt TcpListener v lng nghe ti cng ch nh.

    TcpListener (IPEndPoint)

    To mt TcpListener vi gi tr Endpoint truyn vo.

    TcpListener (IPAddress, Int32)

    To mt TcpListener v lng nghe cc kt ni n ti a ch IP v cng ch nh.

    + Cc phng thc khc

    Name Description

    AcceptSocket Chp nhn mt yu cu kt ni ang ch.

    AcceptTcpClient Chp nhn mt yu cu kt ni ang ch. (ng dng s dng ti lnh ny cho n khi no c mt kt ni n)

    Pending Cho bit liu c kt ni no ang ch i khng ? (True = c).

    Start Bt u lng nghe cc yu cu kt ni.

    Stop Dng vic nghe.

    S dng lp TcpListener ta vit li chng trnh DateTime Server nh sau: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.IO; class DateTimeServer{ static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2009); TcpListener server = new TcpListener(iep); server.Start(); TcpClient client = server.AcceptTcpClient(); StreamReader sr = new StreamReader(client.GetStream()); StreamWriter sw = new StreamWriter(client.GetStream()); string kq=""; while (true) {

  • 24

    string s = sr.ReadLine(); s=s.ToUpper(); if (s.Equals("QUIT")) break; if (s.Equals("GETDATE")) kq = DateTime.Now.ToString("dd/MM/yyyy"); else if (s.Equals("GETTIME")) kq = DateTime.Now.ToString("hh:mm:ss"); else kq = "Khong hieu lenh"; sw.WriteLine(kq); sw.Flush(); } sr.Close(); sw.Close(); client.Close(); } } 2.3.3. Lp UDPClient

    Giao thc UDP (User Datagram Protocol hay User Define Protocol) l mt giao thc

    phi kt ni (Connectionless) c ngha l mt bn c th gi d liu cho bn kia m khng cn

    bit l bn 9 sn sng hay cha ? (Ni cch khc l khng cn thit lp kt ni gia hai

    bn khi tin hnh trao i thng tin). Giao thc ny khng tin cy bng giao thc TCP nhng

    tc li nhanh v d ci t. Ngoi ra, vi giao thc UDP ta cn c th gi cc gi tin qung

    b (Broadcast) cho ng thi nhiu my.

    Trong .NET, lp UDPClient (nm trong System.Net.Sockets) ng gi cc chc nng

    ca giao thc UDP.

    Constructor methosd Description

    UdpClient () To mt i tng (th hin) mi ca lp UDPClient.

    UdpClient (AddressFamily) To mt i tng (th hin) mi ca lp UDPClient. Thuc mt dng a ch (AddressFamily) c ch nh.

    UdpClient (Int32) To mt UdpClient v gn (bind) mt cng cho n.

    UdpClient (IPEndPoint) To mt UdpClient v gn (bind) mt IPEndpoint (gn a ch IP v cng) cho n.

    UdpClient (Int32, AddressFamily) To mt UdpClient v gn s hiu cng, AddressFamily

  • 25

    UdpClient (String, Int32) To mt UdpClient v thit lp vi mt trm t xa mc nh.

    PUBLIC Method

    Name Description

    BeginReceive Nhn d liu Khng ng b t my xa.

    BeginSend Gi khng ng b d liu ti my xa

    Close ng kt ni.

    Connect Thit lp mt Default remote host.

    EndReceive Kt thc nhn d liu khng ng b trn

    EndSend Kt thc vic gi d liu khng ng b trn

    Receive Nhn d liu (ng b) do my xa gi. (ng b c ngha l cc lnh ngay sau lnh Receive ch c thc thi nu Receive 9 nhn c d liu v . Cn nu n cha nhn c d ch mt cht th n vn c ch (blocking))

    Send Gi d liu (ng b) cho my xa.

    V d s dng UdpClient vit chng trnh Chat gia 2 my: Do chng trnh 2 my l nh nhau ta ch cn vit mt chng trnh copy ra s

    dng. Hnh nh ca n nh sau:

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing;

  • 26

    using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace UdpChat { public partial class Form1 : Form { public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void btSend_Click(object sender, EventArgs e) { UdpClient send = new UdpClient(); IPEndPoint iepRemote = new IPEndPoint(IPAddress.Parse(txtIp.Text), int.Parse(txtRemotePort.Text)); byte[] data = new byte[1024]; data = Encoding.UTF8.GetBytes(txtSend.Text); send.Send(data, data.Length, iepRemote); txtReceive.Text += "Sender: "+txtSend.Text + "\r\n"; txtSend.Clear(); if (txtSend.Text.ToUpper().Equals("QUIT")) this.Dispose(); } private void btConnect_Click(object sender, EventArgs e) { Thread tuyen = new Thread(new ThreadStart(NhanDl)); tuyen.Start(); } private void NhanDl() { UdpClient receiver = new UdpClient(int.Parse(txtLocalPort.Text)); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0); while (true) { byte[] data = new byte[1024]; data = receiver.Receive(ref iep); string s = Encoding.UTF8.GetString(data); if (s.Trim().ToUpper().Equals("QUIT")) break; txtReceive.Text += "Receiver: "+ s + "\r\n"; } } } } 2.4. Socket khng ng b

    2.4.1. M hnh x l s kin ca windows

  • 27

    M hnh x l s kin ca Windows c th hin qua hnh sau:

    Nh vy thng qua m hnh ny ta c th y nhim cho mt th tc no thc

    hin khi s kin sy ra trn cc Control

    V d: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace EventDemo { public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += new EventHandler(NhanTiep); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Bac da nhan em"); } private void NhanTiep(object sender, EventArgs e) { MessageBox.Show("Bac lai nhan em roi"); } } } v d trn chng ta ngoi s kin Click ca button 1 chng ta thm mt x kin khi button1 c nhn l s kin NhanTiep. 2.4.2. S dng Socket khng ng b lp trnh khng ng b vi Socket chng ta s dng cc phng thc cho

    vic s dng bt ng b

  • 28

    Cc phng thc cho vic lp trnh bt ng b c chia lm 2 li thng bt u bng Begin v End:

    Phng thc bt u bng Begin, bt u mt chc nng v c ng k vi phng thc AsyncCallback

    Bt u bng End ch chc nng hon thnh khi AsyncCallback c gi.

    EndSendTo() To send data to a

    specific remote host

    BeginSendTo()

    EndSend() To send data from a

    socket

    BeginSend()

    EndReceiveFrom() To retrieve data from a

    specific remote host

    BeginReceiveFrom()

    EndReceive() To retrieve data from a

    socket

    BeginReceive()

    EndConnect() To connect to a remote

    host

    BeginConnect()

    EndAccept() To accept an incoming

    connection

    BeginAccept()

    Requests Ended 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

    - chp nhn kt ni bt ng b ta s dng phng thc BeginAccept() v

    EndAccept() nh sau: Phng thc BeginAccept() v EndAccept()

    IAsyncResult BeginAccept(AsyncCallback callback, object state) Socket EndAccept(IAsyncResult iar);

    Thng c dng nh sau: Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream,

    ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);

    sock.Bind(iep); sock.Listen(5);

    sock.BeginAccept(new AsyncCallback(CallAccept), sock); Trong phng thc CallAccept thng c vit nh sau:

    private static void CallAccept(IAsyncResult iar) { Socket server = (Socket)iar.AsyncState;

    Socket client = server.EndAccept(iar); . . .

    } - thit lp kt ni theo cch bt ng b chng ta s dng phng thc

    BeginConnect() v EndConnect() nh sau: Phng thc BeginConnect() v EndConnect()

  • 29

    Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    IPEndPoint iep =new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock);

    Trong phng thc Connected thng c vit nh sau: public static void Connected(IAsyncResult iar) {

    Socket sock = (Socket)iar.AsyncState; try {

    sock.EndConnect(iar); } catch (SocketException) {

    Console.WriteLine("Unable to connect to host"); }

    } - gi d liu bt ng b chng ta lm nh sau:

    + Phng thc BeginSend() v EndSend() + BeginSend()

    IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags sockflag, AsyncCallback callback, object state)

    V d: sock.BeginSend(data, 0, data.Length, SocketFlags.None, new

    AsyncCallback(SendData), sock); + EndSend()

    int EndSend(IAsyncResult iar) Trong phng thc SendData thng c vit nh sau:

    private static void SendData(IAsyncResult iar) { Socket server = (Socket)iar.AsyncState;

    int sent = server.EndSend(iar); }

    Tng t nh giao thc hng kt ni nu ta s dng gi d liu theo giao thc khng hng kt ni chng ta cng thc hin tng t nh sau:

    Phng thc BeginSendTo() v EndSendTo() IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags

    sockflag, EndPoint ep, AsyncCallback callback, object state) V d: IPEndPoint iep = new EndPoint(IPAddress.Parse("192.168.1.6"), 9050);

    sock.BeginSendTo(data, 0, data.Length, SocketFlags.None, iep, new AsynCallback(SendDataTo), sock);

    int EndSendTo(IAsyncResult iar) - nhn d liu bt ng b ta thc hin nh sau:

    + Nhn d liu vi giao thc hng kt ni:

    Phng thc BeginReceive v EndReceive()

  • 30

    sock.BeginReceive(data, 0, data.Length, SocketFlags.None, new

    AsyncCallback(ReceivedData), sock);

    Vi ReceivedData c nh ngha nh sau:

    void ReceivedData(IAsyncResult iar) {

    Socket remote = (Socket)iar.AsyncState;

    int recv = remote.EndReceive(iar);

    string receivedData = Encoding.ASCII.GetString(data, 0,

    recv);

    Console.WriteLine(receivedData);

    }

    + Nhn d liu bt ng b vi giao thc khng hng kt ni.

    Phng thc BeginReceiveFrom() and EndReceiveFrom()

    sock.BeginReceive(data, 0, data.Length, SocketFlags.None, ref iep, new

    AsyncCallback(ReceiveData), sock);

    void ReceiveData(IasyncResult iar){

    Socket remote = (Socket)iar.AsyncState;

    int recv = remote.EndReceiveFrom(iar);

    string stringData = Encoding.ASCII.GetString(data, 0,

    recv);

    Console.WriteLine(stringData);

    }

    2.4.3. V d v Socket khng ng b Sau y chng ta s s dng cc phng thc khng ng b vit chng trnh Client/Server theo Socket bt ng b, mi khi Client gi d liu ln Server, n s in

    ra v gi tr li cho Client. M hnh ca client/server s dng cc phng thc bt ng b nh sau:

  • 31

    Chng trnh pha Client: using System; using System.Drawing; using System.Net; using System.Net.Sockets; using System.Text; using System.Windows.Forms; class AsyncTcpClient:Form { private TextBox newText; private TextBox conStatus; private ListBox results; private Socket client; private byte[] data = new byte[1024]; private int size = 1024; public AsyncTcpClient() { Text = "Asynchronous TCP Client"; Size = new Size(400, 380); Label label1 = new Label(); label1.Parent = this; label1.Text = "Enter text string:"; label1.AutoSize = true; label1.Location = new Point(10, 30); newText = new TextBox(); newText.Parent = this; newText.Size = new Size(200, 2 * Font.Height); newText.Location = new Point(10, 55); results = new ListBox(); results.Parent = this; results.Location = new Point(10, 85); results.Size = new Size(360, 18 * Font.Height); Label label2 = new Label(); label2.Parent = this;

  • 32

    label2.Text = "Connection Status:"; label2.AutoSize = true; label2.Location = new Point(10, 330); conStatus = new TextBox(); conStatus.Parent = this; conStatus.Text = "Disconnected"; conStatus.Size = new Size(200, 2 * Font.Height); conStatus.Location = new Point(110, 325); Button sendit = new Button(); sendit.Parent = this; sendit.Text = "Send"; sendit.Location = new Point(220,52); sendit.Size = new Size(5 * Font.Height, 2 * Font.Height); sendit.Click += new EventHandler(ButtonSendOnClick); Button connect = new Button(); connect.Parent = this; connect.Text = "Connect"; connect.Location = new Point(295, 20); connect.Size = new Size(6 * Font.Height, 2 * Font.Height); connect.Click += new EventHandler(ButtonConnectOnClick); Button discon = new Button(); discon.Parent = this; discon.Text = "Disconnect"; discon.Location = new Point(295,52); discon.Size = new Size(6 * Font.Height, 2 * Font.Height); discon.Click += new EventHandler(ButtonDisconOnClick); } void ButtonConnectOnClick(object obj, EventArgs ea) { conStatus.Text = "Connecting..."; Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); newsock.BeginConnect(iep, new AsyncCallback(Connected), newsock); } void ButtonSendOnClick(object obj, EventArgs ea) { byte[] message = Encoding.ASCII.GetBytes(newText.Text); newText.Clear(); client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendData), client); } void ButtonDisconOnClick(object obj, EventArgs ea) { client.Close(); conStatus.Text = "Disconnected"; } void Connected(IAsyncResult iar) {

  • 33

    client = (Socket)iar.AsyncState; try { client.EndConnect(iar); conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString(); client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client); } catch (SocketException) { conStatus.Text = "Error connecting"; } } void ReceiveData(IAsyncResult iar) { Socket remote = (Socket)iar.AsyncState; int recv = remote.EndReceive(iar); string stringData = Encoding.ASCII.GetString(data, 0, recv); results.Items.Add(stringData); } void SendData(IAsyncResult iar) { Socket remote = (Socket)iar.AsyncState; int sent = remote.EndSend(iar); remote.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), remote); } public static void Main() { Application.Run(new AsyncTcpClient()); } } Chng trnh pha Server: using System; using System.Drawing; using System.Net; using System.Net.Sockets; using System.Text; using System.Windows.Forms; class AsyncTcpSrvr :Form { private TextBox conStatus; private ListBox results; private byte[] data = new byte[1024]; private int size = 1024; private Socket server; public AsyncTcpSrvr() { Text = "Asynchronous TCP Server"; Size = new Size(400, 380);

  • 34

    results = new ListBox(); results.Parent = this; results.Location = new Point(10, 65); results.Size = new Size(350, 20 * Font.Height); Label label1 = new Label(); label1.Parent = this; label1.Text = "Text received from client:"; label1.AutoSize = true; label1.Location = new Point(10, 45); Label label2 = new Label(); label2.Parent = this; label2.Text = "Connection Status:"; label2.AutoSize = true; label2.Location = new Point(10, 330); conStatus = new TextBox(); conStatus.Parent = this; conStatus.Text = "Waiting for client..."; conStatus.Size = new Size(200, 2 * Font.Height); conStatus.Location = new Point(110, 325); Button stopServer = new Button(); stopServer.Parent = this; stopServer.Text = "Stop Server"; stopServer.Location = new Point(260,32); stopServer.Size = new Size(7 * Font.Height, 2 * Font.Height); stopServer.Click += new EventHandler(ButtonStopOnClick); server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); server.Bind(iep); server.Listen(5); server.BeginAccept(new AsyncCallback(AcceptConn), server); } void ButtonStopOnClick(object obj, EventArgs ea) { Close(); } void AcceptConn(IAsyncResult iar) { Socket oldserver = (Socket)iar.AsyncState; Socket client = oldserver.EndAccept(iar); conStatus.Text = "Connected to: " + client.RemoteEndPoint.ToString(); string stringData = "Welcome to my server"; byte[] message1 = Encoding.ASCII.GetBytes(stringData); client.BeginSend(message1, 0, message1.Length, SocketFlags.None, new AsyncCallback(SendData), client); } void SendData(IAsyncResult iar) { Socket client = (Socket)iar.AsyncState;

  • 35

    int sent = client.EndSend(iar); client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client); } void ReceiveData(IAsyncResult iar) { Socket client = (Socket)iar.AsyncState; int recv = client.EndReceive(iar); if (recv == 0) { client.Close(); conStatus.Text = "Waiting for client..."; server.BeginAccept(new AsyncCallback(AcceptConn), server); return; } string receivedData = Encoding.ASCII.GetString(data, 0, recv); results.Items.Add(receivedData); byte[] message2 = Encoding.ASCII.GetBytes(receivedData); client.BeginSend(message2, 0, message2.Length, SocketFlags.None, new AsyncCallback(SendData), client); } public static void Main() { Application.Run(new AsyncTcpSrvr()); } } 2.4.4. S dng cc phng thc Non-blocking lp trnh bt ng b chng ta c th s dng cc phng thc Non

    bloking nh phng thc Poll() v phng thc Select: + Phng thc Poll()

    bool Poll(int microseconds, SelectMode mode); SelectRead: Poll() tr v true nu mt trong nhng iu kin sau c

    tho: Nu phng thc Accept() thnh cng

    Nu c d liu trn Socket Nu kt ni ng

    SelectWrite: Poll() tr v true nu tho mt trong nhng iu kin sau: Phng thc Connect() thnh cng

    Nu c d liu trn Socket gi SelectError: Poll() tr v true nu mt trong nhng iu kin sau c

    tho: Nu phng thc Connect() tht bi Nu c d liu ngoi bng thng chun gi n nhng thuc tnh

    OutOfBandInline khng c thit lp l true. + Phng thc Select():

  • 36

    Socket.Select(IList checkRead, IList checkWrite, IList checkError, int microseconds)

    checkRead monitors the specified sockets for the ability to read data from the socket.

    checkWrite monitors the specified sockets for the ability to write data to the socket.

    checkError monitors the specified sockets for error conditions.

    V d ng dng Server s dng phng thc Poll() using System; using System.Net; using System.Net.Sockets; using System.Text; class TcpPollSrvr { public static void Main() { int recv; byte[] data = new byte[1024]; IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); newsock.Bind(ipep); newsock.Listen(10); Console.WriteLine("Waiting for a client..."); bool result; int i = 0; while (true) { i++; Console.WriteLine("polling for accept#{0}...", i); result = newsock.Poll(1000000, SelectMode.SelectRead); if (result) { break; } } Socket client = newsock.Accept(); IPEndPoint newclient = (IPEndPoint)client.RemoteEndPoint; Console.WriteLine("Connected with {0} at port {1}", newclient.Address, newclient.Port); string welcome = "Welcome to my test server"; data = Encoding.ASCII.GetBytes(welcome); client.Send(data, data.Length, SocketFlags.None);

  • 37

    i = 0; while (true) { Console.WriteLine("polling for receive #{0}...", i); i++; result = client.Poll(3000000, SelectMode.SelectRead); if (result) { data = new byte[1024]; i = 0; recv = client.Receive(data); if (recv == 0) break; Console.WriteLine( Encoding.ASCII.GetString(data, 0, recv)); client.Send(data, recv, 0); } } Console.WriteLine("Disconnected from {0}", newclient.Address); client.Close(); newsock.Close(); } } Sau y chng ta s vit mt chng trnh Server s dng phng thc Select() chp nhn 2 kt ni n t client v x l tng kt ni.

    Chng trnh Select Server: using System;

    using System.Collections; using System.Net;

    using System.Net.Sockets; using System.Text;

    class SelectTcpSrvr {

    public static void Main() {

    ArrayList sockList = new ArrayList(2); ArrayList copyList = new ArrayList(2);

    Socket main = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); byte[] data = new byte[1024];

    string stringData;

  • 38

    int recv; main.Bind(iep);

    main.Listen(2); Console.WriteLine("Waiting for 2 clients...");

    Socket client1 = main.Accept(); IPEndPoint iep1 = (IPEndPoint)client1.RemoteEndPoint;

    client1.Send(Encoding.ASCII.GetBytes("Welcome to my server")); Console.WriteLine("Connected to {0}", iep1.ToString());

    sockList.Add(client1); Console.WriteLine("Waiting for 1 more client...");

    Socket client2 = main.Accept(); IPEndPoint iep2 = (IPEndPoint)client2.RemoteEndPoint;

    client2.Send(Encoding.ASCII.GetBytes("Welcome to my server")); Console.WriteLine("Connected to {0}", iep2.ToString());

    sockList.Add(client2); main.Close();

    while (true) {

    copyList = new ArrayList(sockList); Console.WriteLine("Monitoring {0} sockets...", copyList.Count);

    Socket.Select(copyList, null, null, 10000000); foreach (Socket client in copyList)

    { data = new byte[1024];

    recv = client.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv);

    Console.WriteLine("Received: {0}", stringData); if (recv == 0)

    { iep = (IPEndPoint)client.RemoteEndPoint;

    Console.WriteLine("Client {0} disconnected.", iep.ToString()); client.Close();

    sockList.Remove(client); if (sockList.Count == 0) {

    Console.WriteLine("Last client disconnected, bye"); return;

    } }

    else client.Send(data, recv, SocketFlags.None);

  • 39

    } }

    } }

    Chng trnh Client: using System;

    using System.Collections; using System.Net;

    using System.Net.Sockets; using System.Text;

    class SelectTcpClient {

    public static void Main() {

    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

    IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); byte[] data = new byte[1024];

    string stringData; int recv;

    sock.Connect(iep); Console.WriteLine("Connected to server");

    recv = sock.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv);

    Console.WriteLine("Received: {0}", stringData); while (true)

    { stringData = Console.ReadLine();

    if (stringData == "exit") break;

    data = Encoding.ASCII.GetBytes(stringData); sock.Send(data, data.Length, SocketFlags.None);

    data = new byte[1024]; recv = sock.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv);

    Console.WriteLine("Received: {0}", stringData); }

    sock.Close(); }

    } 2.5. S dng Thread trong cc ng dng mng

  • 40

    Mt s khi nim - a nhim (Multitasking): L kh nng h iu hnh lm nhiu cng vic ti mt thi

    im - Tin trnh (Process): Khi chy mt ng dng, h iu hnh s cp pht ring cho ng dng b nh v cc ti nguyn khc. B nh v ti nguyn vt l ring bit ny

    c gi l mt tin trnh. Cc ti nguyn v b nh ca mt tin trnh th ch tin trnh c php truy cp.

    - Tuyn (Thread): Trong h thng, mt tin trnh c th c mt hoc nhiu chui thc hin tch bit nhau v c th chy ng thi. Mi chui thc hin ny c gi l mt tuyn (Thread). Trong mt ng dng, Thread khi to u tin gi l Thread s cp

    hay Thread chnh.

    2.5.1. S dng Thread trong chng trnh .Net s dng Thread trong .Net ta s dng NameSpace System.Threading

    - Mt s phng thc thng dng

    Public Method Name

    M t

    Abort() Kt thc Thread

    Join() Buc chng trnh phi ch cho thread kt thc (Block) th mi thc hin tip (cc cu lnh ng sau Join).

    Resume() Tip tc chy thread b tm ngng - suspended.

    Sleep() Static method : Tm dng thread trong mt khong thi gian.

    Start() Bt u chy (khi ng) mt thread. Sau khi gi phng thc ny, trng thi ca thread chuyn t trng thi hin hnh sang Running.

    Suspend() Tm ngng (ngh) thread. (Phng thc ny b loi khi phin bn VS.NET 2005)

    - Mt s thuc tnh thng dng:

    Public Property Name

    M t

    CurrentThread This static property: Tr v thread hin hnh ang chy.

    IsAlive Tr v gi tr cho bit trng thi thc thi ca thread hin hnh.

    IsBackground Sets or gets gi tr cho bit l thread l background hay foreground thread.

    IsThreadPoolThread Gets a value indicating whether a thread is part of a thread pool.

    Priority Sets or gets gi tr ch nh u tin (dnh nhiu hay t CPU cho thread). Cao nht l 4, thp nht l 0.

  • 41

    Public Property Name

    M t

    ThreadState Ly v trng thi ca thread (ang dng, hay ang chy)

    - To mt tuyn trong C# Thread newThread=newThread(new ThreadStart(newMethod)); . } void newMethod() { . . . } 2.5.2. S dng Thread trong cc chng trnh Server - a tuyn hay c ng dng trong cc chng trnh Server, cc chng trnh i hi ti mt thi im chp nhn nhiu kt ni n t cc Client. - cc chng trnh Server c th x l nhiu Client ti mt thi im ta c m hnh ng dng a tuyn nh sau:

    Sau y chng ta vit li chng trnh DateTimeServer c s dng Thread nh sau: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; using System.IO; class Program { static void Main(string[] args) { IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2009); TcpListener server = new TcpListener(iep); server.Start(); while (true) {

  • 42

    //chap nhan ket noi TcpClient client= server.AcceptTcpClient(); //Tao ra tuyen moi de xu ly moi Client new ClientThread(client); } server.Stop(); } } class ClientThread { private Thread tuyen; private TcpClient client; public ClientThread(TcpClient client) { this.client = client; tuyen = new Thread(new ThreadStart(GuiNhanDL)); tuyen.Start(); } private void GuiNhanDL() { StreamReader sr = new StreamReader(client.GetStream()); StreamWriter sw= new StreamWriter(client.GetStream()); string kq=""; while(true) { string s=sr.ReadLine(); s=s.ToUpper(); if(s.Equals("QUIT")) break; if(s.Equals("GETDATE")) kq=DateTime.Now.ToString("dd/MM/yyyy"); else if(s.Equals("GETTIME")) kq=DateTime.Now.ToString("hh:mm:ss"); else kq="Khong hieu lenh"; sw.WriteLine(kq); sw.Flush(); } client.Close(); } } 2.5.3. S dng Thread gi/nhn d liu ng dng a tuyn trong vic gi nhn d liu chng ta vit chng trnh Chat theo giao thc TCP nh sau:

  • 43

    ng dng m hnh x l s kin ca Windows v a tuyn v Socket khng ng b ta ch cn vit mt chng trnh sau dch ra, ta chy ng dng nhn Listen

    n s lng nghe trong vai tr Server cn khi ta chy v nhn Connect n s ng vai tr Client v kt ni ti Server.

    Vn bn chng trnh nh sau: using System; using System.Drawing; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading;

  • 44

    using System.Windows.Forms; class TcpChat:Form { private static TextBox newText; private static ListBox results; private static Socket client; private static byte[] data = new byte[1024]; public TcpChat() { Text = "TCP Chat Program"; Size = new Size(400, 380); Label label1 = new Label(); label1.Parent = this; label1.Text = "Enter text string:"; label1.AutoSize = true; label1.Location = new Point(10, 30); newText = new TextBox(); newText.Parent = this; newText.Size = new Size(200, 2 * Font.Height); newText.Location = new Point(10, 55); results = new ListBox(); results.Parent = this; results.Location = new Point(10, 85); results.Size = new Size(360, 18 * Font.Height); Button sendit = new Button(); sendit.Parent = this; sendit.Text = "Send"; sendit.Location = new Point(220,52); sendit.Size = new Size(5 * Font.Height, 2 * Font.Height); sendit.Click += new EventHandler(ButtonSendOnClick); Button connect = new Button(); connect.Parent = this; connect.Text = "Connect"; connect.Location = new Point(295, 20); connect.Size = new Size(6 * Font.Height, 2 * Font.Height); connect.Click += new EventHandler(ButtonConnectOnClick); Button listen = new Button(); listen.Parent = this; listen.Text = "Listen"; listen.Location = new Point(295,52); listen.Size = new Size(6 * Font.Height, 2 * Font.Height); listen.Click += new EventHandler(ButtonListenOnClick); } void ButtonListenOnClick(object obj, EventArgs ea) { results.Items.Add("Listening for a client..."); Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

  • 45

    IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); newsock.Bind(iep); newsock.Listen(5); newsock.BeginAccept(new AsyncCallback(AcceptConn), newsock); } void ButtonConnectOnClick(object obj, EventArgs ea) { results.Items.Add("Connecting..."); client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050); client.BeginConnect(iep, new AsyncCallback(Connected), client); } void ButtonSendOnClick(object obj, EventArgs ea) { byte[] message = Encoding.ASCII.GetBytes(newText.Text); newText.Clear(); client.BeginSend(message, 0, message.Length, 0, new AsyncCallback(SendData), client); } void AcceptConn(IAsyncResult iar) { Socket oldserver = (Socket)iar.AsyncState; client = oldserver.EndAccept(iar); results.Items.Add("Connection from: " + client.RemoteEndPoint.ToString()); Thread receiver = new Thread(new ThreadStart(ReceiveData)); receiver.Start(); } void Connected(IAsyncResult iar) { try { client.EndConnect(iar); results.Items.Add("Connected to: " + client.RemoteEndPoint.ToString()); Thread receiver = new Thread(new ThreadStart(ReceiveData)); receiver.Start(); } catch (SocketException) { results.Items.Add("Error connecting"); } } void SendData(IAsyncResult iar) { Socket remote = (Socket)iar.AsyncState; int sent = remote.EndSend(iar); } void ReceiveData() { int recv;

  • 46

    string stringData; while (true) { recv = client.Receive(data); stringData = Encoding.ASCII.GetString(data, 0, recv); if (stringData == "bye") break; results.Items.Add(stringData); } stringData = "bye"; byte[] message = Encoding.ASCII.GetBytes(stringData); client.Send(message); client.Close(); results.Items.Add("Connection stopped"); return; } public static void Main() { Application.Run(new TcpChat()); } } 2.5.4. S dng ThreadPool trong cc chng trnh .Net

    Method Description

    BindHandle() Binds an operating system handle to the thread pool

    GetAvailableThreads() Gets the number of worker threads available for use in the thread pool

    GetMaxThreads() Gets the maximum number of worker threads available in the thread pool

    QueueUserWorkItem() Queues a user delegate to the thread pool

    RegisterWaitForSingleObject() Registers a delegate waiting for a WaitHandle object

    UnsafeQueueUserWorkItem() Queues an unsafe user delegate to the thread pool but does not propagate the calling stack onto the worker thread

    UnsafeRegisterWaitForSingleObject() Registers an unsafe delegate waiting for a WaitHandle object

    using System;

    using System.Threading;

    class ThreadPoolSample

    {

  • 47

    public static void Main()

    {

    ThreadPoolSample tps = new ThreadPoolSample();

    }

    public ThreadPoolSample()

    {

    int i;

    ThreadPool.QueueUserWorkItem(new WaitCallback(Counter));

    ThreadPool.QueueUserWorkItem(new WaitCallback(Counter2));

    for(i = 0; i < 10; i++)

    {

    Console.WriteLine("main: {0}", i);

    Thread.Sleep(1000);

    }

    }

    void Counter(object state)

    {

    int i;

    for (i = 0; i < 10; i++)

    {

    Console.WriteLine(" thread: {0}", i);

    Thread.Sleep(2000);

    }

    }

    void Counter2(object state)

    {

    int i;

    for (i = 0; i < 10; i++)

    {

    Console.WriteLine(" thread2: {0}", i);

    Thread.Sleep(3000);

    }

    }

    }

    2.5.5. S dng ThreadPool trong cc chng trnh Server using System;

    using System.Net;

    using System.Net.Sockets;

    using System.Text;

    using System.Threading;

    class ThreadPoolTcpSrvr

    {

    private TcpListener client;

    public ThreadPoolTcpSrvr()

    {

    client = new TcpListener(9050);

    client.Start();

    Console.WriteLine("Waiting for clients...");

    while(true)

    {

    while (!client.Pending())

    {

    Thread.Sleep(1000);

    }

    ConnectionThread newconnection = new ConnectionThread();

    newconnection.threadListener = this.client;

    ThreadPool.QueueUserWorkItem(new

    WaitCallback(newconnection.HandleConnection));

    }

    }

    public static void Main()

    {

    ThreadPoolTcpSrvr tpts = new ThreadPoolTcpSrvr();

  • 48

    }

    }

    class ConnectionThread

    {

    public TcpListener threadListener;

    private static int connections = 0;

    public void HandleConnection(object state)

    {

    int recv;

    byte[] data = new byte[1024];

    TcpClient client = threadListener.AcceptTcpClient();

    NetworkStream ns = client.GetStream();

    connections++;

    Console.WriteLine("New client accepted: {0} active connections",

    connections);

    string welcome = "Welcome to my test server";

    data = Encoding.ASCII.GetBytes(welcome);

    ns.Write(data, 0, data.Length);

    while(true)

    {

    data = new byte[1024];

    recv = ns.Read(data, 0, data.Length);

    if (recv == 0)

    break;

    ns.Write(data, 0, recv);

    }

    ns.Close();

    client.Close();

    connections;

    Console.WriteLine("Client disconnected: {0} active connections",

    connections);

    }

    }

    2.6. K thut IP Multicasting

    2.6.1. Broadcasting l g? Broadcast, ting Vit gi l qung b. Trong h thng mng hu tuyn, qung b l

    thut ng dng ch vic gi mt gi thng tin n tt cc nt mng trong mng.

    thc hin hnh thc qung b, a ch n ca gi tin s l a ch qung b.

    C hai loi l: Local Broadcast v Global Broadcast

    2.6.2. S dng Broadcasting gi d liu n nhiu my trong mng cc b Gi gi d liu Broadcast using System; using System.Net; using System.Net.Sockets; using System.Text; class BadBroadcast { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 9050); byte[] data = Encoding.ASCII.GetBytes("This is a test message"); sock.SendTo(data, iep); sock.Close(); }

  • 49

    } Chng ta phi thit lp nh sau: class Broadcst { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep1 = new IPEndPoint(IPAddress.Broadcast, 9050); IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 9050); string hostname = Dns.GetHostName(); byte[] data = Encoding.ASCII.GetBytes(hostname); sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); sock.SendTo(data, iep1); sock.SendTo(data, iep2); sock.Close(); } } Nhn gi d liu Broadcast class RecvBroadcst { public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork,SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); sock.Bind(iep); EndPoint ep = (EndPoint)iep; Console.WriteLine("Ready to receive"); byte[] data = new byte[1024]; int recv = sock.ReceiveFrom(data, ref ep); string stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString()); data = new byte[1024]; recv = sock.ReceiveFrom(data, ref ep); stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}",stringData, ep.ToString()); sock.Close(); } } 2.6.3. Multicasting l g? Mt a ch multicast cho php thit b gi d liu ti mt tp xc nh trc cc host,

    c bit n nh cc nhm multicast, trong cc mng con khc nhau.

    Mt s a ch Multicast

    a ch multicast Chc nng

    224.0.0.0 a ch c s

    224.0.0.1 Tt c cc h thng trn mng con ny

    224.0.0.2 Tt c cc Router trn mng con ny

  • 50

    224.0.0.5 Cc DR trong OSPF

    224.0.1.9 Nhm a ch RIPv2

    224.0.1.24 Nhm a ch WINS server

    C 2 k thut Multicast c s dng

    + Peer to Peer

    + Central Server

    2.6.4. Socket Multicasting trong .Net

    S dng phng thc SetSocketOption()

  • 51

    Socket option c th c s dng

    Thm mt Socket vo nhm Multicast

    Loi mt Socket khi nhm Multicast

    SetSocketOption(SocketOptionLevel,SocketOptionName, optionValue)

    SocketOptionName

    AddMembership

    DropMembership

    S dng phng thc SetSocketOption()

    Socket option c th c s dng

    optionValue l mt i tng ca lp MulticastOption

    MulticastOption(IPAddress) MulticastOption(IPAddress,IPAddress)

    V d thm mt Socket vo nhm Multicast 224.100.0.1

    sock.SetSocketOption(SocketOptionLevel.IP,

    SocketOptionName.AddMembership, new

    MulticastOption(IPAddress.Parse("224.100.0.1"));

    Gi d liu Multicast class MultiSend{ public static void Main() { Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050); byte[] data = Encoding.ASCII.GetBytes("This is a test message"); server.SendTo(data, iep); server.Close(); } } Nhn d liu Multicast class MultiRecv{ public static void Main() { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); Console.WriteLine("Ready to receive"); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); EndPoint ep = (EndPoint)iep; sock.Bind(iep); sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.100.0.1"))); byte[] data = new byte[1024]; int recv = sock.ReceiveFrom(data, ref ep); string stringData = Encoding.ASCII.GetString(data, 0, recv); Console.WriteLine("received: {0} from: {1}", stringData, ep.ToString()); sock.Close(); } }

  • 52

    Gi d liu Multicast vi TTL class NewMultiSend{ public static void Main() { Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9051); IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050); server.Bind(iep); byte[] data = Encoding.ASCII.GetBytes("This is a test message"); server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("224.100.0.1"))); server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 50); server.SendTo(data, iep2); server.Close(); } }

    Multicast vi lp UdpClient

    JoinMulticastGroup()

    DropMulticastGroup()

    JoinMulticastGroup() l phng thc overload

    JoinMulticastGroup(IPAddress)

    JoinMulticastGroup(IPAddress, int)

    class UdpClientMultiSend{ public static void Main() { UdpClient sock = new UdpClient(); IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050); byte[] data = Encoding.ASCII.GetBytes("This is a test message"); sock.Send(data, data.Length, iep); sock.Close(); } } class UdpClientMultiRecv { public static void Main() { UdpClient sock = new UdpClient(9050); Console.WriteLine("Ready to receive"); sock.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0); byte[] data = sock.Receive(ref iep); string stringData = Encoding.ASCII.GetString(data, 0, data.Length); Console.WriteLine("received: {0} from: {1}", stringData, iep.ToString()); sock.Close(); } }

  • 53

    2.7 Bi tp p dng

    class MulticastChat : Form{ TextBox newText;

    ListBox results; Socket sock; Thread receiver;

    IPEndPoint multiep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050); public MulticastChat() { Text = "Multicast Chat Program";

    Size = new Size(400, 380); Label label1 = new Label(); label1.Parent = this;

    label1.Text = "Enter text string:"; label1.AutoSize = true;

    label1.Location = new Point(10, 30); newText = new TextBox(); newText.Parent = this;

    newText.Size = new Size(200, 2 * Font.Height); newText.Location = new Point(10, 55); results = new ListBox();

    results.Parent = this; results.Location = new Point(10, 85);

    results.Size = new Size(360, 18 * Font.Height); Button sendit = new Button(); sendit.Parent = this;

    sendit.Text = "Send"; sendit.Location = new Point(220, 52); sendit.Size = new Size(5 * Font.Height, 2 * Font.Height);

    sendit.Click += new EventHandler(ButtonSendOnClick); Button closeit = new Button();

    closeit.Parent = this; closeit.Text = "Close"; closeit.Location = new Point(290, 52);

    closeit.Size = new Size(5 * Font.Height, 2 * Font.Height); closeit.Click += new EventHandler(ButtonCloseOnClick); sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,

    ProtocolType.Udp); IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050); sock.Bind(iep);

    sock.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,

  • 54

    new MulticastOption(IPAddress.Parse("224.100.0.1"))); receiver = new Thread(new ThreadStart(packetReceive));

    receiver.IsBackground = true; receiver.Start(); }

    void ButtonSendOnClick(object obj, EventArgs ea) { byte[] message = Encoding.ASCII.GetBytes(newText.Text);

    newText.Clear(); sock.SendTo(message, SocketFlags.None, multiep); }

    void ButtonCloseOnClick(object obj, EventArgs ea) { receiver.Abort(); sock.Close();

    Close(); } void packetReceive() {

    EndPoint ep = (EndPoint)multiep; byte[] data = new byte[1024];

    string stringData; int recv; while (true) {

    recv = sock.ReceiveFrom(data, ref ep); stringData = Encoding.ASCII.GetString(data, 0, recv); results.Items.Add("from " + ep.ToString() + ": " + stringData);

    } }

    public static void Main() { Application.Run(new MulticastChat()); }

    }

  • 55

    CHNG 3: XY DNG NG DNG MNG

    3.1. Giao thc ICMP

    Gii thiu giao thc ICMP (Internetwork Control Message Protocol)

    - Giao thc ICMP hot ng trn layer 2 - Internetwork trong m hnh TCP/IP hoc

    layer 3 - Network trong m hnh OSI

    Cho php kim tra v xc nh li ca Layer 3 Internetwork trong m hnh TCP/IP

    bng cch nh ngha ra cc loi thng ip c th s dng xc nh xem mng hin

    ti c th truyn c gi tin hay khng.

    Trong thc t, ICMP cn cc thnh phn ca mi gi tin IP c th hot ng c.

    Cu trc ca gi tin IP v ICMP

    + Type: c th l mt query hay mt li

    + Code: Xc nh y l loi query hay thng ip li

    + Checksum: Kim tra v sa li cho d liu ICMP

    + Message: Tu thuc vo Type v Code

    3.1.1. S dng Raw Socket Gi tin ICMP khng s dng TCP hoc UDP nn chng ta khng th s dng cc lp

    c h tr nh TcpClient hay UdpClient m phi s dng mt Raw Socket

    Mun to Raw Socket khi to ra Socket bn s dng SocketType.Raw, giao thc

    ICMP

    To Raw Socket nh sau

    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw,

    ProtocolType.Icmp);

    Raw Socket Format

    Value Description

    Ggp Gateway-to-Gateway Protocol

    Icmp Internet Control Message Protocol

  • 56

    Idp IDP Protocol

    Igmp Internet Group Management Protocol

    IP A raw IP packet

    Ipx Novell IPX Protocol

    ND Net Disk Protocol

    Pup Xerox PARC Universal Protocol (PUP)

    Raw A raw IP packet

    Spx Novell SPX Protocol

    SpxII Novell SPX Version 2 Protocol

    Unknown An unknown protocol

    Unspecified An unspecified protocol

    Gi gi d liu Raw

    ICMP l giao thc khng hng kt ni

    S dng phng thc SendTo() ca lp Socket gi

    Cng trong giao thc ICMP khng quan trng

    IPEndPoint iep = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 0);

    sock.SendTo(packet, iep);

    Nhn gi d liu Raw

    S dng phng thc ReceiveForm ca lp Socket

    D liu nhn v l mt gi tin IP chng ta phi tch ra ly gi tin ICMP

    Raw Socket khng t ng nh dng gi tin ICMP cho chng ta. Chng ta phi t lm

    Data Variable Size Type

    Type 1 byte Byte

    Code 1 byte Byte

    Checksum 2 bytes Unsigned 16-bit integer

    Message multibyte Byte array

    nh ngha lp v phng thc khi to mc nh

    class ICMP {

    public byte Type;

    public byte Code;

    public UInt16 Checksum;

    public int Messagesize;

    public byte[] Message = new byte[1024];

    public ICMP() {

    }

    }

    To ra gi tin ICMP

    ICMP packet = new ICMP();

  • 57

    packet.Type = 0x08;

    packet.Code = 0x00;

    packet.Checksum = 0;

    public ICMP(byte[] data, int size) {

    Type = data[20];

    Code = data[21];

    Checksum = BitConverter.ToUInt16(data, 22);

    MessageSize = size - 24;

    Buffer.BlockCopy(data, 24, Message, 0, MessageSize);

    }

    public byte[] getBytes() {

    byte[] data = new byte[MessageSize + 9];

    Buffer.BlockCopy(BitConverter.GetBytes(Type), 0, data, 0, 1);

    Buffer.BlockCopy(BitConverter.GetBytes(Code), 0, data, 1, 1);

    Buffer.BlockCopy(BitConverter.GetBytes(Checksum), 0, data, 2, 2);

    Buffer.BlockCopy(Message, 0, data, 4, MessageSize);

    return data;

    }

    public UInt16 getChecksum() {

    UInt32 chcksm = 0;

    byte[] data = getBytes();

    int packetsize = MessageSize + 8;

    int index = 0;

    while (index < packetsize) {

    chcksm += Convert.ToUInt32(BitConverter.ToUInt16(data, index));

    index += 2;

    }

    chcksm = (chcksm >> 16) + (chcksm & 0xffff);

    chcksm += (chcksm >> 16);

    return (UInt16)(~chcksm);

    }

    3.1.2. S dng giao thc ICMP v Raw Socket xy dng chng trnh Ping

  • 58

    class Program { static void Main(string[] args) { byte[] data = new byte[1024]; int recv; Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); IPEndPoint iep = new IPEndPoint(IPAddress.Parse(argv[0]), 0); EndPoint ep = (EndPoint)iep; ICMP packet = new ICMP(); packet.Type = 0x08; packet.Code = 0x00; packet.Checksum = 0; Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 0, 2); Buffer.BlockCopy(BitConverter.GetBytes((short)1), 0, packet.Message, 2, 2); data = Encoding.ASCII.GetBytes("test packet"); Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length); packet.MessageSize = data.Length + 4; int packetsize = packet.MessageSize + 4; UInt16 chcksum = packet.getChecksum(); packet.Checksum = chcksum; host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000); host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep); try { data = new byte[1024]; recv = host.ReceiveFrom(data, ref ep); } catch (SocketException) { Console.WriteLine("No response from remote host"); return; } ICMP response = new ICMP(data, recv); Console.WriteLine("response from: {0}", ep.ToString()); Console.WriteLine(" Type {0}", response.Type); Console.WriteLine(" Code: {0}", response.Code); int Identifier = BitConverter.ToInt16(response.Message, 0);

  • 59

    int Sequence = BitConverter.ToInt16(response.Message, 2); Console.WriteLine(" Identifier: {0}", Identifier); Console.WriteLine(" Sequence: {0}", Sequence); string stringData = Encoding.ASCII.GetString(response.Message, 4, response.MessageSize - 4); Console.WriteLine(" data: {0}", stringData); host.Close(); } } 3.1.3. S dng giao thc ICMP v Raw Socket xy dng chng trnh TraceRoute class TraceRoute { public static void Main(string[] argv) { byte[] data = new byte[1024]; int recv, timestart, timestop; Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp); IPHostEntry iphe = Dns.Resolve(argv[0]); IPEndPoint iep = new IPEndPoint(iphe.AddressList[0], 0); EndPoint ep = (EndPoint)iep; ICMP packet = new ICMP(); packet.Type = 0x08; packet.Code = 0x00; packet.Checksum = 0; Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 0, 2); Buffer.BlockCopy(BitConverter.GetBytes(1), 0, packet.Message, 2, 2); data = Encoding.ASCII.GetBytes("test packet"); Buffer.BlockCopy(data, 0, packet.Message, 4, data.Length); packet.MessageSize = data.Length + 4; int packetsize = packet.MessageSize + 4; UInt16 chcksum = packet.getCchecksum(); packet.Checksum = chcksum; host.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000); int badcount = 0; for (int i = 1; i < 50; i++) { host.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, i); timestart = Environment.TickCount; host.SendTo(packet.getBytes(), packetsize, SocketFlags.None, iep); try { data = new byte[1024]; recv = host.ReceiveFrom(data, ref ep); timestop = Environment.TickCount; ICMP response = new ICMP(data, recv); if (response.Type == 11) Console.WriteLine("hop {0}: response from {1}, {2}ms", i, ep.ToString(), timestop - timestart); if (response.Type == 0) { Console.WriteLine("{0} reached in {1} hops, {2}ms.", ep.ToString(), i, timestop - timestart);