標籤:
using System;using System.IO;using System.Net;using System.Net.Sockets;using System.Text;namespace ConsoleApplication2{ public class Program { public static void Main(string[] args) { //取得預儲存的檔案名稱 string fileName = "index.html"; //遠程主機 string hostName = "www.baidu.com"; //連接埠 int port = 80; //得到主機資訊 IPHostEntry ipInfo = Dns.GetHostByName(hostName); //取得IPAddress[] IPAddress[] ipAddr = ipInfo.AddressList; //得到ip IPAddress ip = ipAddr[0]; //組合出遠程終結點 IPEndPoint hostEP = new IPEndPoint(ip, port); //建立Socket 執行個體 Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { //嘗試串連 socket.Connect(hostEP); } catch (Exception se) { Console.WriteLine(se.Message); } //發送給遠程主機的請求內容串 string sendStr = "GET / HTTP/1.1\r\nHost: " + hostName + "\r\nConnection: Close\r\n\r\n"; //建立bytes位元組數組以轉換髮送串 byte[] bytesSendStr = new byte[1024]; //將發送內容字串轉換成位元組byte數組 bytesSendStr = Encoding.ASCII.GetBytes(sendStr); try { //向主機發送請求 socket.Send(bytesSendStr, bytesSendStr.Length, 0); } catch (Exception ce) { Console.WriteLine(ce.Message); } //聲明接收返回內容的字串 string recvStr = ""; //聲明位元組數組,一次接收資料的長度為1024位元組 byte[] recvBytes = new byte[1024]; //返回實際接收內容的位元組數 int bytes = 0; //迴圈讀取,直到接收完所有資料 while (true) { bytes = socket.Receive(recvBytes, recvBytes.Length, 0); //讀取完成後退出迴圈 if (bytes <= 0) break; //將讀取的位元組數轉換為字串 recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes); } //將所讀取的字串轉換為位元組數組 byte[] content = Encoding.ASCII.GetBytes(recvStr); try { //建立檔案流對象執行個體 FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); //寫入檔案 fs.Write(content, 0, content.Length); } catch (Exception fe) { Console.WriteLine(fe.Message); } //禁用Socket socket.Shutdown(SocketShutdown.Both); //關閉Socket socket.Close(); } }}
C# Socket編程