用Socket類構建網頁下載器
2024-07-21 02:17:15
供稿:網友
 
用socket類構建網頁下載器
            屠恩海(sunhai)
   開發工具:microsoft visual studio .net 2003
   操作系統:windows xp
               什么時候用到socket類
   microsoft.net framework為應用程序訪問internet提供了分層的、可擴展的以及受管轄的網絡服務,其名字空間system.net和system.net.sockets包含豐富的類可以開發多種網絡應用程序。所謂“分層”,可以視為包含3個層次:請求/響應層、應用協議層、傳輸層。webreqeust和webresponse 代表了請求/響應層,支持http、tcp和udp的類組成了應用協議層,而socket類處于最底層——傳輸層。《用httpwebrequest和正則表達式提取網頁中的鏈接》一文介紹了用請求/響應層來取得網頁源代碼。本文則用最底層的傳輸層來取得網頁源代碼。
  為什么要用socket?或者什么時候要用到socket?
  socket 類為網絡通信提供了一套豐富的方法和屬性。 socket 類允許您使用下面列出的任何一種協議執行異步和同步數據傳輸:
ggp
 網關到網關協議。 
icmp
 網際消息控制協議。 
idp
 idp 協議。 
igmp 網際組管理協議。 
ip 網際協議。 
ipv6 網際協議 v6。 
ipx ipx 協議。 
nd 網絡磁盤協議(非正式)。 
pup pup 協議。 
raw 原始 up 包協議。 
spx spx 協議。 
spxii spx 版本 2 協議。 
tcp 傳輸控制協議。 
udp 用戶數據文報協議。 
unknown 未知協議。 
unspecified 未指定的協議。 
  當您需要開發功能復雜的網絡程序時,您可能要用到socket類。
   
  
              用socket類取得網頁源代碼      
  先引入以下命名空間:
imports system.net
imports system.net.sockets
imports system.io
imports system.text
imports system.text.encoding 
  我原來用c#來練習本文代碼,c#嚴格區分大小寫,且智能感知的功能顯然不如vb.net,代碼雖然簡潔了,但一開始不太適應。我想,microsoft真正主推的或許是vb.net,不然為何不在c#中實現同vb.net一樣的智能感知功能?最終還是用vb.net來寫本文代碼。
  初學者對socket類的使用可能有點茫然,不要緊,先從簡單的實例開始,實例調試成功,再去詳細了解理論知識也不遲。
private sub btnhtml_click(byval sender as system.object, byval e as system.eventargs) handles btnhtml.click
  dim serverip as ipaddress = dns.resolve("http://sunhai.tianyablog.com").addresslist(0)
  ' default web server port = 80
  dim port as string = "80"
  dim serverhost as new ipendpoint(serverip, int32.parse(port))
  dim clientsocket as new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp)
  try
    clientsocket.connect(serverhost)
    if clientsocket.connected = false then
      msgbox("connect error.", msgboxstyle.critical, "http")
      exit sub
    end if
    dim httpreq as string = "get / http/1.0" & controlchars.crlf & controlchars.crlf
    clientsocket.send(ascii.getbytes(httpreq))
    dim buffer(1024) as byte
    dim bytecount as int16 = clientsocket.receive(buffer, buffer.length, 0)
    txthtml.text = ascii.getstring(buffer, 0, bytecount)
    do while bytecount > 0
      bytecount = clientsocket.receive(buffer, buffer.length, 0)
      txthtml.text = txthtml.text & ascii.getstring(buffer, 0, bytecount)
    loop
  catch ex as exception
    msgbox(ex.stacktrace.tostring(), msgboxstyle.critical, "exception")
  end try
end sub
 
與我聯系:
我的qq:  26624998
我的網站:http://sunhai.tianyablog.com
本文地址:http://www.csdn.net/develop/read_article.asp?id=25281
   
網絡資源:
windows socket 網絡編程——套接字編程原理
visual c#托管socket的實現方法 
c#網絡編程初探
visual c#.net 網絡程序開發-socket篇
淺析c#中的套接字編程