2013-05-04 238 views
1

我想给通过TCP连接字符串:发送和接收纯文本与TCP

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,*

我使用此代码来发送的文字:

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; 
} 

发送此请求后,在对方的应用程序,我得到th是字符串:

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(); 

和ListenForClients方法(一些代码为清楚起见省略):

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); 
} 

我的问题是为什么发送和接收的字符串是不一样?

+0

任何你需要在发送端使用HTTP的原因?你会碰到其他实际上是HTTP服务器的服务器吗? – Slugart 2013-05-04 07:29:44

+0

我使用了完全相同的代码,并收到了标题和正文。 HTTPWebRequest类将始终添加HTTP标头,因为它是HTTP协议的一部分。 – Slugart 2013-05-04 07:40:37

回答

2

你确定你知道你在做什么吗?你正在发送HTTP包到一个原始的TCP套接字,当然你会得到你的真正有效载荷的HTTP协议字符串。两端使用相同类型的插座,否则最终会发疯。

这是稍微旧的,但似乎足够满足您的需要,像往常一样:Google是你的朋友。

http://www.codeproject.com/Articles/12893/TCP-IP-Chat-Application-Using-C

至于为什么TCP套接字正在接收顺利HTTP连接? HTTP是通过TCP运行的,它只是一个正式的协议。