使用最簡易的方法實現http傳輸 返回固定數值html
public partial class Form1 : Form { static Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //偵聽socket public Form1() { InitializeComponent(); } private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { string c = CookieReader.GetCookie("http://10.33.208.230/uac/"); this.textBox1.Text = c; Program.cookie = c; this.Text = "服務端:" + webBrowser1.Document.Title; } private void Form1_Shown(object sender, EventArgs e) { _socket.Bind(new IPEndPoint(IPAddress.Any, 8123)); _socket.Listen(100); _socket.BeginAccept(new AsyncCallback(OnAccept), _socket); } /// <summary> /// 接受處理http的請求 /// </summary> /// <param name="ar"></param> static void OnAccept(IAsyncResult ar) { try { Socket socket = ar.AsyncState as Socket; Socket web_client = socket.EndAccept(ar); //接收到來自瀏覽器的代理socket //NO.1 並行處理http請求 socket.BeginAccept(new AsyncCallback(OnAccept), socket); //開始下一次http請求接收 (此行代碼放在NO.2處時,就是串行處理http請求,前一次處理過程會阻塞下一次請求處理) byte[] recv_Buffer = new byte[1024 * 640]; int recv_Count = web_client.Receive(recv_Buffer); //接收瀏覽器的請求數據 string recv_request = Encoding.UTF8.GetString(recv_Buffer, 0, recv_Count); //Resolve(recv_request, web_client); //解析、路由、處理 string content = Program.cookie; byte[] cont = Encoding.UTF8.GetBytes(content); sendPageContent(cont, web_client); //NO.2 串行處理http請求 } catch (Exception ex) { //writeLog("處理http請求時出現異常!" + Environment.NewLine + "\t" + ex.Message); } } static void sendPageContent(byte[] pageContent, Socket response) { string statusline = "HTTP/1.1 200 OK\r\n"; //狀態行 byte[] statusline_to_bytes = Encoding.UTF8.GetBytes(statusline); byte[] content_to_bytes = pageContent; string header = string.Format("Content-Type:text/html;charset=UTF-8\r\nContent-Length:{0}\r\n", content_to_bytes.Length); byte[] header_to_bytes = Encoding.UTF8.GetBytes(header); //應答頭 response.Send(statusline_to_bytes); //發送狀態行 response.Send(header_to_bytes); //發送應答頭 response.Send(new byte[] { (byte)'\r', (byte)'\n' }); //發送空行 response.Send(content_to_bytes); //發送正文(html) response.Close(); } }