How to get page via TcpClient?

亡梦爱人 提交于 2019-12-05 17:33:21

The problem is that ReadToEnd only returns when the stream has ended. Unfortunately, the server keeps the TCP connection alive. Therefore ReadToEnd can never detect that the true end has arrived.

Proof:

                        sw.Write(request);
                        sw.Flush();
                        var l = sr.ReadLine();

l is being filled with the first line of the request.

Remove the keep-alive header and add:

Connection: close

Or use the response Content-Length header to correctly read it (binary).

    A simple example is this:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Web;
    using System.Data;
    using System.Collections;
    using System.Collections.Specialized;
    using System.Windows.Forms;

    //Some "using" may not be needed
    static public TcpListener listener = new TcpListener(IPAddress.Any, 8080);

     static void Main(string[] args)
            {
             listener.Start();
             TcpClient client = listener.AcceptTcpClient();
             StreamReader sr = new StreamReader(client.GetStream());
             sr.ReadLine();
            }



**For asynchronous Connection:**


 static void Main(string[] args)
     {
       client_listener();
     }
async static public void client_listener()
        {
            while (true)
            {
                listener.Start();
                TcpClient client = await listener.AcceptTcpClientAsync();
                StreamReader sr = new StreamReader(client.GetStream());
                try
                {
                    await sr.ReadLineAsync();
                }
                catch(Exception e)
                {
                }
        }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!