i want to use socket to connect www.google.com and test it.but there is something wrong with it.
[Terminal]Code:int mysocket = socket(AF_INET,SOCK_STREAM,0); NSLog(@"mysocket=%d\n",mysocket); struct sockaddr_in sa; bzero(&sa, sizeof(sa)); sa.sin_family = AF_INET; sa.sin_port = htons(80); sa.sin_addr.s_addr = inet_addr(@"www.google.com"); int len = sizeof(sa); int nRet = connect(mysocket,(struct sockaddr *)&sa,len); if(nRet == 0) { NSLog(@"success!\n"); } else { NSLog(@"error! %d\n",errno); errno=2] } char buf[] ="GET / 1.0\r\n User-Agent: Mozilla/5.0\r\n accept: */*\r\n\r\n"; nRet = send(mysocket,buf,sizeof(buf),0); if(nRet == sizeof(buf)) { NSLog(@"nRet=%d!\n",nRet); } else { NSLog(@"nRet=%d!\n",nRet); } if(nRet >0 ) { char buffer[40000]; bzero(buffer,sizeof(buffer)); nRet= 0; int nTotal = 0; while(nRet >0) { nRet = recv(mysocket,&buffer[nTotal],2048,0); if(nRet>0) nTotal+=nRet; } if(nTotal > 0) { } else { NSLog(@"recv error\n"); } } else { NSLog(@"send error\n"); }
2008-01-15 18:11:11.688 hello[560:d03] mysocket=9
2008-01-15 18:11:11.713 hello[560:d03] error! 2
2008-01-15 18:11:11.716 hello[560:d03] nRet=-1!
when i use the following code ,it works ok!!
Then why? why does the socket run error? Any one can help me?Code:NSMutableURLRequest *theRequest; NSString* theURL = [NSMutableString stringWithString:@"http://www.google.com"]; theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:theURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0]; [theRequest setHTTPMethod:@"GET"]; [theRequest setValue:@"*/*\r\n\r\n" forHTTPHeaderField:@"accept"]; [theRequest setValue:@"Close" forHTTPHeaderField:@"Connection"]; urlConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
Thanks to all!



LinkBack URL
About LinkBacks








Reply With Quote
Bookmarks