使用最简易的方法实现http传输 返回固定数值
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(); } }