1

早上好,

我读完 Beej 的网络编程指南以刷新我对 C 网络概念的记忆。

对于我正在构建的应用程序的下一部分,我希望用户能够使用端口(例如 8080)通过 Web 浏览器连接到他们的 iPhone/iDevice。

因此,出于测试目的,我自己尝试了一下,但遇到了一些意想不到的问题。我将一个端口绑定到内核并等待传入​​连接。为了模拟远程用户,我进入我的网络浏览器并输入 localhost:8080

我在整个应用程序中设置的 NSLog 和 printf() 消息表明我确实连接了,我什至通过显示连接用户的 IP 地址来验证它,但应用程序的客户端没有按预期运行。我在我的服务器代码中向客户端发送 HTML,但没有显示任何内容。这是我到目前为止的代码

- (void) start
{

   struct addrinfo hints ,*res;
   struct sockaddr_storage connectionInfo;

   socklen_t connectionSize;
   memset(&hints,0,sizeof(hints));
   hints.ai_family = AF_INET;
   hints.ai_socktype = SOCK_STREAM;
   hints.ai_flags = AI_PASSIVE;
   int status;
   if((status = getaddrinfo(NULL,"8080",&hints,&res) )!= 0)
   {
       NSLog(@"Error inding getaddrinfo..");
       printf("%s",gai_strerror(status));

       return;
   }


   int sockFd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);

   int yes = 1;
   setsockopt(sockFd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int));

   if(sockFd < 0)
   {
       NSLog(@"Error on the socket() call");
       printf("%s",gai_strerror(sockFd));
       freeaddrinfo(res);
       return;
   }

   NSLog(@"Made the socket connection!");

   if(bind(sockFd , res->ai_addr, res->ai_addrlen) < 0)
   {
       NSLog(@"Bind error!");
       freeaddrinfo(res);
       return;


   } 


   if(listen(sockFd,10) < 0)
   {
       NSLog(@"Unable to listen!");
       freeaddrinfo(res);
       return;
   }
   printf("Listening for a connection\n");

   connectionSize = sizeof(connectionInfo);

   int new_fd = accept(sockFd,(struct sockaddr*)&connectionInfo,&connectionSize);

   const char* data = "<html><head><title> hi </title><body><h1> Test</h1> 
     </body></head></html>";
   send(new_fd,data,strlen(data),0);
   if(new_fd < 0)
   {
       NSLog(@"Cannot communicate with the new_fd");
       freeaddrinfo(res);
       printf("%s",gai_strerror(new_fd));
       return;
   }
   NSLog(@"Communication with the new_fd!!!");
   struct sockaddr_in whoAreThey;
   socklen_t size = sizeof(whoAreThey);
   getpeername(new_fd, (struct sockaddr*)&whoAreThey, &size);
   char theirIp[16];
   void* addrPtr = &(whoAreThey.sin_addr);
   inet_ntop(AF_INET, addrPtr, theirIp, sizeof(theirIp));
   NSLog(@"IP Address ");
   printf("%s  Connected\n",theirIp);
   NSLog(@"The data were sent");
   close(sockFd);
   freeaddrinfo(res);





}

在我的 viewDidLoad 方法中,我这样调用 start :

- (void) viewDidLoad
{
      [super viewDidLoad];  
      [self start];

}

为什么客户端(网络浏览器)不显示 HTML?谢谢

注意:我知道数据正在发送,因为使用 telnet localhost 8080 向我提供了 HTML

4

1 回答 1

2

您没有阅读浏览器的请求。浏览器可能不会读取您的数据,除非您完全读取它发送给您的数据。

因此,在应该解决您的问题recv之前的循环(直到没有来自浏览器的更多数据) 。send

编辑:最终解决方案是响应行没有发送到浏览器。违规行是:

const char* data = "<html><head><title> hi </title></head><body><h1> Test</h1></body></html>";

应该是:

const char* data = "HTTP/1.0 200 OK\r\n\r\n<html><head><title> hi </title></head><body><h1> Test</h1></body></html>";
于 2012-12-26T17:04:17.573 回答