おはようございます、
Beej のネットワーク プログラミング ガイドを読み終えて、C ネットワークの概念についての記憶を新たにしました。
私が構築しているアプリケーションの次の部分では、ユーザーがポート (たとえば 8080) を使用して Web ブラウザー経由で iPhone/iDevice に接続できるようにしたいと考えています。
テスト目的で自分で試してみましたが、予期しない問題が発生しました。ポートをカーネルにバインドし、着信接続を待ちます。リモート ユーザーをシミュレートするには、Web ブラウザーに移動し、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];
}
クライアント (Web ブラウザ) に HTML が表示されないのはなぜですか? ありがとう
注:telnet localhost 8080を使用するとHTMLがフィードされるため、データが送信されていることはわかっています