110,567
社区成员
发帖
与我相关
我的任务
分享
TcpClient tcpClient = new TcpClient();
Uri URI = new Uri("http://192.168.18.66/getData");
tcpClient.Connect(URI.Host, URI.Port);
NetworkStream netStream = tcpClient.GetStream();
if (netStream.CanWrite)
{
string msg = "name=aabb11";
StringBuilder sb = new StringBuilder();
sb.Append("POST " + URI.PathAndQuery + " HTTP/1.0\r\n");
sb.Append("Host: " + URI.Host + "\r\n");
sb.Append("Content-Type: application/x-www-form-urlencoded\r\n");
sb.Append("Content-Length: " + Encoding.UTF8.GetByteCount(msg) + "\r\n");
sb.Append("\r\n");
sb.Append(msg + "\r\n");
Byte[] sendBytes = Encoding.UTF8.GetBytes(sb.ToString());
netStream.Write(sendBytes, 0, sendBytes.Length);
netStream.Flush();
}
if (netStream.CanRead)
{
Thread.Sleep(10); //这个地方加上就能获取到数据,如果去掉大部分时候都不能获取到,只有少数时候能取得
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
netStream.Read(bytes, 0, (int)tcpClient.ReceiveBufferSize);
string returndata = Encoding.UTF8.GetString(bytes);
returndata = returndata.Substring(0,returndata.IndexOf('\0'));
Console.WriteLine("returns: " + returndata);
}
tcpClient.Close();
netStream.Close();