【问题标题】:C++/TCP data transfer garbageC++/TCP 数据传输垃圾
【发布时间】:2012-10-14 17:28:21
【问题描述】:

我是一名初学者 C++/TCP 程序员,我正在做一个在 C++/VS2010/Windows 7 中使用 TCP 传输文件的家庭作业。

我创建了一个客户端和一个服务器,可以监听网络上的多个客户端。 当我向服务器发送请求文件的请求时,我收到了正确大小的文件,但是当我从服务器向客户端发送数据时,我得到了垃圾。

我很确定我在投射的某个地方犯了一个愚蠢的错误,但无法确定在哪里。 我正在逐字节发送char* 并将它们保存到客户端上的文件中。

任何想法有什么问题吗?

// client code: 
unsigned int packlen = 0;
unsigned int flength = 0;
char* data = NULL;
if((packlen = recv(sock, (char*) &flength, sizeof(unsigned int), 0)) == 
    sizeof(unsigned int))
{
    flength = (unsigned int) flength;
    data = new char[flength];
}
unsigned char current;
char* buffer;
unsigned int accumlength = 0;

for(unsigned int i = 0; i < flength; ++i)
{
    if((packlen = recv(sock, (char*) &current , sizeof(unsigned int), 0)) 
        != sizeof(unsigned int))
    {
        err_sys("Receiving packet transfer error., exit");
    }
    data[i] = current;
}
ofstream output(argv[2], ios::binary);
output.write(data, flength);
if(data)
{
    delete[] data;
    data = NULL;
}


// Server code:
char* data = NULL;
unsigned long length;
string fname; 

data = new char[stat_buf.st_size];
ifstream input(reqp->filename, ios::binary);
input.seekg(0, ios::end);
unsigned int length = input.tellg();
if(length != stat_buf.st_size)
{
    err_sys("Problems with file size");
}

send(cs, (char*) &length, sizeof(unsigned int), 0);
Sleep(1000);  // wait a bit

input.read(data, length); // read all file at once.
for(unsigned int i = 0; i < length; ++i)
{
    unsigned char current = data[i];
    send(cs, (char*) &current, sizeof(unsigned char), 0);
}

感谢您的帮助。

【问题讨论】:

  • recv(sock, (char*) &amp;current , sizeof(unsigned int), 0) 看起来很奇怪。 current 是单个字符,除非您有非常大的字符,否则您无法将 unsigned int 的数据读入其中。
  • 您在服务器端为每个字节发送一个unsigned char,但在客户端接收unsigned int
  • 对不起,我的错误类型匹配错误。
  • 现在我正在这样做: for(unsigned int i = 0; i

标签: c++ tcp


【解决方案1】:

看起来您在读取循环期间丢弃了很多字节:

recv(sock, (char*) &current, sizeof(unsigned int), 0)

其中current 是一个无符号字符,但您要求它读取更多的sizeof(unsigned int) 字节。所以 recv() 会将其结果写入其他地方(因为它会在current 中写入 4 个字节)

你应该写:

recv(sock, (char*) &current, 1, 0)

即使这非常低效,它至少应该可以工作。

【讨论】:

  • 我已经这样做了,但它仍然是垃圾......我使用 send(cs, (char*) &current, 1, 0); 逐字节传输一个 jpg 文件在服务器上和 recv(sock, (char*) &current , 1, 0) 在客户端上,结果是垃圾......我不明白为什么......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 2015-02-23
  • 2014-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多