1

我想通过 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;
}

发送此请求后,在另一端应用程序中,我得到了这个字符串:

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

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

4

1 回答 1

2

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

这有点旧,但似乎足以满足您的需求,一如既往:谷歌是您的朋友。

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

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

于 2013-05-04T06:42:36.300 回答