使用TcpClient向服务器发送请求

时间:2012-08-24 15:11:37

标签: c# http webserver tcpclient

我问这个问题主要是因为我没有明确的想法。我相信我理解网络服务器是如何工作的,但出于某种原因,我得到的结果与预期不同。

所以基本上我想用真实的网页浏览器复制我的代码。

我有一个名为Fiddler的程序,它充当代理,以便查看来自Web服务器的所有请求和响应。

1。因此,当我打开我的broser然后转到http://10.10.10.28/tfs:8080时,这就是显示的内容:

-------- enter image description here

。 。 。 。这就是小提琴手的记录:

enter image description here

当我点击取消或尝试登录其他请求时,fiddler将记录更多数据。我并不关心这是正确的知道我只是对模拟这个第一个请求感兴趣。

无论如何,如此提琴手告诉我们标题是:

GET http://10.10.10.28/tfs:8080 HTTP/1.1
Host: 10.10.10.28
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

并且回复是:

HTTP/1.1 401 Unauthorized
Server: Microsoft-IIS/7.5
WWW-Authenticate: Negotiate
WWW-Authenticate: NTLM
X-Powered-By: ASP.NET
MicrosoftSharePointTeamServices: 12.0.0.6421
Date: Fri, 24 Aug 2012 14:36:22 GMT
Content-Length: 0
Proxy-Support: Session-Based-Authentication

2。最后到代码的有趣部分现在我想发送相同的标题并期望获得相同的响应。 出于某种原因,我得到了不同的回复!

public static void Main(string[] args)
{
    // I save the header bytes recorded from fiddler on a file to make sure I am sending the exact same request
    byte[] header = System.IO.File.ReadAllBytes(@"C:\Users\Antonio\Desktop\header");

    // create the client
    TcpClient client = new TcpClient("10.10.10.28", 8080);

    // get the stream so that we can read and write to it
    var stream = client.GetStream();

    // now that we have the stream wait for the server to respond
    WaitForResponse(stream); // waits on a separate thread

    // send the request to the header
    stream.Write(header, 0, header.Length);

    // wait
    Console.Read();
}

public static void WaitForResponse(NetworkStream stream)
{
    Task.Factory.StartNew(() => {
        byte[] buffer = new byte[16384];
        int responseLength = stream.Read(buffer, 0, buffer.Length);
        string resp = System.Text.UTF8Encoding.UTF8.GetString(buffer, 0, responseLength);
        resp = resp; // place breakpoint
    });
    System.Threading.Thread.Sleep(10); // make sure task starts
}

这是我得到的回复: enter image description here

为什么我会得到不同的回复?我认为Web服务器使用tcp连接向客户端发送页面。为什么我采取的这种方法不起作用?另外当我从代码向网络服务器发送请求时,为什么小提琴手不记录任何内容? Google Chrome如何连接到网络服务器?我敢打赌,Chrome浏览器也正在建立与Web服务器的tcp连接。

3 个答案:

答案 0 :(得分:1)

您正在连接到其他服务器(端口8080与端口80)。

此外,来自fiddler的请求看起来不正确。 GET未指定方法或主机名。也许这些数据已被按摩以使其看起来更友好?

我希望请求的第一行看起来更像GET /tfs:8080 HTTP/1.1

答案 1 :(得分:1)

在您的示例中,您连接到端口8080并请求URL http://10.10.10.28/tfs:8080。因此,您连接到端口8080,然后从端口80请求某些内容。这会导致Bad Request的响应。

答案 2 :(得分:0)

您试图在不先写入请求的情况下阅读流,这就是问题所在。

为什么不使用HttpWebRequest而不是TcpClient?

相关问题