適合剛接觸socket和http的人
註釋比較全面
方法的返回數據是我爲了方便調用並取得調用結果的
如果不需要可以去掉
GETHTML方法返回的數據就是取得的網頁HTML代碼
可以利用字符串拆分 /r/n/r/n 注意是兩個哦
分出報頭和內容
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Net.Sockets;
- using System.Net;
- using System.IO;
- namespace 貼吧江湖
- {
- public class clsSocket
- {
- private Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //創建socket 連接
- IPHostEntry IpHost;
- public int CreatSocket(string strUrl, int intPort)
- {
- try
- {
- IpHost = Dns.Resolve(strUrl);//解析主機地址
- }
- catch (Exception)
- {
- return 5;
- }
- IPAddress ip = IpHost.AddressList[0]; //獲取主機IP
- IPEndPoint ipe = new IPEndPoint(ip, intPort); //創建IPEndPoint實例
- try
- {
- s.Connect(ipe);//嘗試連接
- }
- catch (ArgumentNullException ae) //處理參數爲空引用異常
- {
- Console.WriteLine("ArgumentNullException : {0}", ae.ToString());
- return 1;
- }
- catch (SocketException se) //處理操作系統異常
- {
- Console.WriteLine("SocketException : {0}", se.ToString());
- return 2;
- }
- catch (Exception es)
- {
- Console.WriteLine("Unexpected exception : {0}", es.ToString());
- return 3;
- }
- return 0;
- }
- public string GetHtml()
- {
- string sendStr = "GET /bbs/ HTTP/1.1/r/n";
- sendStr += "Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-ms-application, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-ms-xbap, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-shockwave-flash, */*/r/n";
- sendStr += "Accept-Language: zh-cn/r/n";
- sendStr += "Host: " + IpHost.HostName + "/r/n";
- sendStr += "Connection: Keep-Alive/r/n/r/n";//創建報文頭
- byte[] bytesSendStr = new byte[1024];// 創建bytes字節數組以轉換髮送串
- bytesSendStr = Encoding.ASCII.GetBytes(sendStr); //將發送內容字符串轉換成字節byte數組
- try
- {
- s.Send(bytesSendStr, bytesSendStr.Length, 0);//向主機發送請求
- }
- catch (Exception ce)
- {
- return ce.Message;
- }
- string recvStr = ""; //聲明接收返回內容的字符串
- byte[] recvBytes = new byte[1024];//聲明字節數組,一次接收數據的長度爲1024字節
- int bytes = 0;//返回實際接收內容的字節數,循環讀取,直到接收完所有數據
- while (true)
- {
- bytes = s.Receive(recvBytes, recvBytes.Length, 0);
- if (bytes <= 0)//讀取完成後退出循環
- break;
- Encoding gb2312 = Encoding.GetEncoding("gb2312");//將讀取的字節數轉換爲字符串
- recvStr += gb2312.GetString(recvBytes, 0, bytes);
- }
- return recvStr;
- }
- public void CloseSocket()
- {
- s.Shutdown(SocketShutdown.Both);
- s.Close();
- }
- }
- }
寫入文本的代碼
- //將所讀取的字符串轉換爲字節數組
- byte[] content = Encoding.ASCII.GetBytes(recvStr);
- try
- {
- //創建文件流對象實例
- FileStream fs = new FileStream("fileName.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
- //寫入文件
- fs.Write(content, 0, content.Length);
- }
- catch (Exception fe)
- {
- MessageBox.Show("文件創建/寫入錯誤:" + fe.Message, "提示信息", MessageBoxButtons.RetryCancel, MessageBoxIcon.Information);
- }