Socket.Receive奇怪 [英] Socket.Receive strangeness

查看:104
本文介绍了Socket.Receive奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿所有,我有以下函数来简单地从套接字上读取一个流,我已经看到了很多关于如何做到这一点的例子但是我已经到达了这个:

Hey all, I have the following function to simply read from a stream on a socket, I've seen lots of examples of how to do this but I've arrived at this:

 

 

string getData(TcpClient client)
{
Socket con = client.Client;
List<byte> theBytes = new List<byte>();

do
{
byte[] down = new byte[1];
con.Receive(down, 1, SocketFlags.None);
//result += ASCIIEncoding.ASCII.GetString(down, 0, received);
theBytes.Add(down[0]);
}
while (con.Available > 0);


byte[] yy = theBytes.ToArray();
string done = ASCIIEncoding.ASCII.GetString(yy, 0, yy.Length);
Console.Writeline("done"); // This sometimes executes twice?! but the method is entered once?!

return done;

}

 

 

将套接字传递给Web浏览器时,这样可以正常工作浏览器GET请求,将正确的文本拉出来。

This works fine when passing it a socket to a web browser e.g. browser GET request, pulls out the correct text fine.

但是当我读到一个插入代码文本的套接字时,我会感到有些奇怪:

But when I read a socket where text from code is sent I get some weirdness:

示例字符串向下发送套接字输入:"HTTP / 1.1 200 OK \\\\ n内容类型:text / plain \\\\ n内容长度:5 \\\\\\\\\ n Hello" ;;

example string send down the socket input: "HTTP/1.1 200 OK \r\n Content-Type:text/plain \r\n Content-Length:5 \r\n\r\n Hello";

示例输出:"Ttlin \\ otn-egh4 \\\\ el" (这可能每次都随机变化)

example output: "Ttlin\\ otn-egh4\\\\ el" (this can vary randomly every time)

输出中的字符显然是原始字符串的一个子集,所以有些在传输过程中丢失了吗?每次都发生

The characters in the output are clearly a subset of the original string, so have some been lost in transit? Happens every time

 

我做些傻事吗?我写入套接字的代码是:

Am I doing somethign silly? my code to write to the socket is:

 

byte[] tt = ASCIIEncoding.ASCII.GetBytes("Some text");
incoming_connection.GetStream().Write(tt,0,tt.Length);
incoming_connection.GetStream().Flush();

 

推荐答案

发现我的问题,

Found my problem,

 

好像我在两个不同的部分同一个套接字上调用了Socket.Receive该程序

seems like I had made calls to Socket.Receive on the same socket in two different parts of the program

 

因此有两个电话竞争数据,因此我只获得了部分文本我正在看的代码行。

Thus there were two calls competing for the data, and thus why I was only getting parts of the text in the line of code I was looking at.

 

doh!


这篇关于Socket.Receive奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆