2

我正处于用 C 编写基本代理服务器的最后一个主要障碍。

我的服务器成功地接收了来自浏览器的请求,然后成功地将它们发送到主机,无论它们在哪里。我也成功收到了楼主的回复!除了,这是我尝试通过服务器连接到 Google 时得到的结果:

Rcvd message from server: 

----

HTTP/1.1 200 OK
Date: Thu, 15 Mar 2012 20:35:11 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=83a7c2e6675a9a9f:FF=0:TM=1331843711:LM=1331843711:S=7I7RIVV1B-HxhWJR; expires=Sat, 15-Mar-2014 20:35:11 GMT; path=/; domain=.google.com
Set-Cookie: NID=57=KvqnXtYNkJZBryXL5zzhG5eH8Or2_PDWDqT_kU35PvOro_mAFiLiTSjPHOnWWxxm3R0vKYnzEeVkAPFKK366lZiNZGpjhO2-II5OeZQnWe09H-jZdePsrN-SnBdQ2ENT; expires=Fri, 14-Sep-2012 20:35:11 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked

1000
<!doctype html><html itemscope itemtype="http://schema.org/WebPage"><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta name="description" content="Search the world&#39;s information, including webpages, images, videos and more. Goo

你看到它是如何切断的吗?因为“传输编码:分块”。现在如何让服务器继续向我发送其余的块?因为在第一个之后,它就停止了。我是否需要将 read() 放入 while 循环中,并说只要有要阅读的内容就继续阅读并转发给客户端吗?

编辑:

好的,这是我现在的代码。这会首先读取服务器的响应(在名为“sock”的套接字上),将其写入客户端(“newsock”),然后进入一个 while 循环以继续读取更多服务器响应并将它们发送到客户端。我还没有测试过这种形式的代码。除了一些错误检查差距之外,您还看到任何明显的问题吗?

/*WRITING SERVER RESPONSE TO CLIENT*/

  char buffer2[1024];

  n = read(sock, buffer2, 1024 );

  if ( n < 1 )
  {
    perror( "read() failed" );
    return EXIT_FAILURE;
  }

  else
  {
    buffer2[n] = '\0';
    printf( "Rcvd message from server: \n\n----\n\n%s\n\n----\n\n", buffer2 );
  }

  n = write( newsock, buffer2, strlen( buffer2 ) );

  while((n = read(sock, buffer2, 1024 )) >= 1)
  {
      buffer2[n] = '\0';
      printf( "Rcvd message from server: \n\n----\n\n%s\n\n----\n\n", buffer2 );
      n = write( newsock, buffer2, strlen( buffer2 ) );
  }
4

1 回答 1

1

您不能使用 strlen 来获取缓冲区的大小, strlen 仅用于获取字符串的大小,您可能正在读取一些二进制数据,因为不仅有文本通过您的代理(图像...) . 尝试使用 read 返回的值,即实际读取的字节数。

用 '\n' 结束你的字符串变得毫无用处。

于 2012-03-16T02:47:37.030 回答