从最后一个字节的套接字读取

时间:2014-10-08 19:59:45

标签: c sockets tcp streaming

server.c

bytesReceived = 0;
    char buff[256];
    char* buffFile;
    char tempbuff;
    bytesReceived = read(clnt_fd, &tempbuff, 1);
    buffFile = (char*)malloc(sizeof(char));
    buffFile[0]=tempbuff;
    long incr=1;
    while(bytesReceived > 0 )
    {

        bytesReceived = read(clnt_fd, &tempbuff, 1);
        incr++;
        buffFile = (char*)realloc(buffFile, sizeof(char)*incr);
        buffFile[incr-1]=tempbuff;

    }

client.c

char filebuff[20];
strcpy(filebuff, "UPC ");
strcat(filebuff, file_size); //it's the file size
strcat(filebuff, " ");

write(clnt_fd, filebuff, strlen(filebuff));


while(1)
  {
  int nread = fread(file_bytes,1,256,fp);
  bytesSent = write(clnt_fd, file_bytes, nread);

  if(bytesSent<0) 
    {
      printf( "Error: %s\n", strerror( errno ) );
      break;
    }
  if(nread<256)
    {
        char t='\n';
        bytesSent = write(clnt_fd, &t, 1);
        break;
    }

}

所以基本上,客户端会发送这样的消息,我必须放一个&#39; \ n&#39;作为最后一个字节。

UPC 5624 bytesbytesbytesetcetc\n

服务器应接收我放入数组中的那些字节,以便对其进行标记,并从数组中获取这些字节以将其写入文件中。问题是,我做了一个计数器,我看到从客户端发送了多少字节,以及每次循环结束时接收了多少字节,我在最后一个字节检查了我的服务器阻止读取功能并挂起。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我不是一个真正的C ++人,但似乎在你进入while循环之前,你执行'read'。当你进入循环时,你再次执行'read',这似乎有点奇怪。

同样做'incr ++;'在while循环范围的底部。因为你已经开始偏移1。在您阅读/使用incr之前,您已经增加了incr。 然后你不必在缓冲区数组中执行incr-1(因为你在while循环的第一次迭代中也错过了bufFile [0]的第一个元素)

刚提到它,不知道这解决了你的问题(用手机键盘回答......)

相关问题