C# 使用TCP发送和接收纯文本
我想通过TCP连接发送此字符串:C# 使用TCP发送和接收纯文本,c#,.net,tcp,tcplistener,C#,.net,Tcp,Tcplistener,我想通过TCP连接发送此字符串: TR220,210000xx,3545.17435119.5794001.01503,52:56:162012/09/13,0,0,0,0,0,V,000,0,0,0,+989123456789,* 我正在使用此代码发送文本: string uri = "http://localhost:1414"; String record = "TR220,2,A10000XX,3545.1743,5119.5794,001.0,1503,52:56:16,2012/09
TR220,210000xx,3545.17435119.5794001.01503,52:56:162012/09/13,0,0,0,0,0,V,000,0,0,0,+989123456789,*
我正在使用此代码发送文本:
string uri = "http://localhost:1414";
String record = "TR220,2,A10000XX,3545.1743,5119.5794,001.0,1503,52:56:16,2012/09/13,0,0,0,0,0,V,000,0,0,0,,+989123456789,*";
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(uri);
request.Method = "POST";
byte[] postBytes = GetBytes(record);
request.ContentType = "text/plain";
request.ContentLength = postBytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
和GetBytes方法:
private byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
发送此请求后,在另一端应用程序中,我得到以下字符串:
POST / HTTP/1.1\r\nContent-Type: text/plain\r\nHost: localhost:1414\r\nContent-Length: 212\r\nExpect: 100-continue\r\nConnection: Keep-Alive\r\n\r\n
使用此代码块:
tcpListener = new TcpListener(IPAddress.Any, 1414);
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
和listenforcients方法(为了清晰起见,省略了一些代码):
我的问题是,为什么发送和接收的字符串不一样?您确定知道自己在做什么吗?您正在向原始TCP套接字发送HTTP数据包,当然,您将在实际负载周围获得HTTP协议字符串。在两端使用同样的插座,否则你最终会发疯的 这有点陈旧,但似乎已经足够满足你的需要了,一如往常:谷歌是你的朋友
至于为什么TCP套接字能够顺利地接收HTTP连接?HTTP是通过TCP运行的,它只是TCP之上的一个正式协议。您为什么需要在发送端使用HTTP?你会攻击其他实际上是HTTP服务器的服务器吗?我使用了与你完全相同的代码,收到了头和正文。HTTPWebRequest类将始终添加HTTP头,因为这是HTTP协议的一部分。
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try { bytesRead = clientStream.Read(message, 0, 4096); }
catch { break; }
ASCIIEncoding encoder = new ASCIIEncoding();
String data = encoder.GetString(message, 0, bytesRead);
MessageReceived(data);
}