gpt4 book ai didi

c# - TcpClient 无法通过流正确发送数据

转载 作者:行者123 更新时间:2023-12-01 19:45:55 29 4
gpt4 key购买 nike

我想使用 TcpClient 发送 HTTP 请求。考虑以下代码:

        byte[] buf = new byte[1024];
string header = "GET http://w3.org HTTP/1.1\r\n" +
"Host: localhost:2006\r\n" +
"Connection: keep-alive\r\n" +
"User-Agent: Mozilla/5.0\r\n" +
"\r\n";

var client = new TcpClient();
client.Connect("w3.org", 80);

// send request
var stream = client.GetStream();
var streamReader = new StreamReader(stream);
var streamWriter = new StreamWriter(stream);

client.Client.Send(System.Text.Encoding.ASCII.GetBytes(header));
//streamWriter.Write(header); - DOES NOT WORK
stream.Flush();
// get response

var response1 = streamReader.ReadLine();

问题是,当我尝试使用客户端的 Send 方法发送数据时 - 一切正常。当我尝试通过网络流提供数据时 - 应用程序挂起并且没有抛出异常。你能告诉我可能出现的问题吗?

最佳答案

StreamWriter还有一个内部缓冲区,需要刷新:

byte[] buf = new byte[1024];
string header = "GET http://w3.org HTTP/1.1\r\n" +
"Host: localhost:2006\r\n" +
"Connection: keep-alive\r\n" +
"User-Agent: Mozilla/5.0\r\n" +
"\r\n";

var client = new TcpClient();
client.Connect("w3.org", 80);

// send request
var stream = client.GetStream();
var streamReader = new StreamReader(stream);
var streamWriter = new StreamWriter(stream);

streamWriter.Write(header);
streamWriter.Flush();
stream.Flush();

// get response
var response1 = streamReader.ReadLine();

关于c# - TcpClient 无法通过流正确发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28327303/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com