http://blog.csdn.net/dongfengsun/article/details/4802925
文章有一些错误
#define KENTER @"/r/n"
应该为
#define KENTER @"\r\n\n"
另外原文中的buffer设置太小,只有512,地址设置为百度的话会因为太小读不到信息,改成1024即可
char readBuffer[512];
改成 char readBuffer[1024];
修改后日志输出:read datas length is :559
PS:改成google会达到令人发指的973.。。。~~
read datas length is :973
改了一些error和warning,版权归原作者所有
1 #import <UIKit/UIKit.h> 2 3 #define MYPORT 4880 4 #import <stdio.h> 5 #import <stdlib.h> 6 #import <unistd.h> 7 #import <arpa/inet.h> 8 #import <sys/types.h> 9 #import <sys/socket.h> 10 #import <netdb.h> 11 12 @interface BSDHttpExampleViewController : UIViewController { 13 int sockfd; 14 struct sockaddr_in their_addr; 15 } 16 17 @end
1 #import "BSDHttpExampleViewController.h" 2 3 @interface BSDHttpExampleViewController() 4 @end 5 6 @implementation BSDHttpExampleViewController 7 8 #define HTTPMETHOD @"GET" 9 #define HTTPVERSION @"HTTP/1.1" 10 #define HTTPHOST @"Host" 11 12 //#define KENTER @"/r/n" 13 #define KENTER @"\r\n\n" 14 #define KBLANK @" " 15 16 /* 17 // The designated initializer. Override to perform setup that is required before the view is loaded. 18 - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { 19 if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) { 20 // Custom initialization 21 } 22 return self; 23 } 24 */ 25 26 /* 27 // Implement loadView to create a view hierarchy programmatically, without using a nib. 28 - (void)loadView { 29 } 30 */ 31 32 33 void error_handle(char *errorMsg) 34 { 35 fputs(errorMsg, stderr); 36 fputc('\n',stderr); 37 exit(1); 38 } 39 40 41 - (NSMutableString*) makeHttpHeader:(NSString*) hostName 42 { 43 NSMutableString *header = [[NSMutableString alloc] init]; 44 45 [header appendFormat:HTTPMETHOD]; 46 [header appendFormat:KBLANK]; 47 [header appendFormat:@"/index.html"]; 48 [header appendFormat:KBLANK]; 49 [header appendFormat:HTTPVERSION]; 50 [header appendFormat:KENTER]; 51 [header appendFormat:HTTPHOST]; 52 [header appendFormat:@":"]; 53 //[header appendFormat:hostName]; 54 [header appendString:hostName]; 55 [header appendFormat:KENTER]; 56 [header appendFormat:KENTER]; 57 58 NSLog(@"header is %@",header); 59 60 return header; 61 } 62 63 - (NSString*)getIpAddressForHost:(NSString*) theHost 64 { 65 struct hostent *host = gethostbyname([theHost UTF8String]); 66 67 if(!host) 68 { 69 herror("resolv"); 70 return NULL; 71 } 72 73 struct in_addr **list = (struct in_addr **)host->h_addr_list; 74 NSString *addressString = [NSString stringWithCString:inet_ntoa(*list[0]) encoding:NSASCIIStringEncoding]; 75 //= [NSString stringWithCString:inet_ntoa(*list[0])]; 76 return addressString; 77 } 78 79 - (void)Connect:(NSString *)hostName content:(NSString *)contentSended 80 { 81 if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) 82 { 83 perror("socket"); 84 exit(1); 85 } 86 87 //NSHost *host = [NSHost hostWithName:hostName]; 88 89 //if(host) 90 //{ 91 their_addr.sin_family = AF_INET; 92 93 //their_addr.sin_addr.s_addr = inet_addr([[host address] UTF8String]); 94 their_addr.sin_addr.s_addr = inet_addr([[self getIpAddressForHost:hostName] UTF8String]); 95 NSLog(@"getIpAddressForHost :%@",[self getIpAddressForHost:hostName]); 96 97 their_addr.sin_port = htons(80); 98 bzero(&(their_addr.sin_zero), 8); 99 100 int conn = connect(sockfd, (struct sockaddr*)&their_addr, sizeof(struct sockaddr)); 101 102 NSLog(@"Connect errno is :%d",conn); 103 if(conn != -1) 104 { 105 NSLog(@"Then the conn is not -1!"); 106 107 NSMutableString* httpContent = [self makeHttpHeader:hostName]; 108 109 NSLog(@"httpCotent is :%@",httpContent); 110 111 if(contentSended != nil) 112 //[httpContent appendFormat:contentSended]; 113 [httpContent appendString:contentSended]; 114 115 NSLog(@"Sended content is :%@",httpContent); 116 117 NSData *data = [httpContent dataUsingEncoding:NSISOLatin1StringEncoding]; 118 ssize_t dataSended = send(sockfd, [data bytes], [data length], 0); 119 120 if(dataSended == [data length]) 121 { 122 NSLog(@"Datas have been sended over!"); 123 } 124 //printf("send %d bytes to %s\n",dataSended,inet_ntoa(their_addr.sin_addr)); 125 126 printf("send %zd bytes to %s\n",dataSended,inet_ntoa(their_addr.sin_addr)); 127 128 NSMutableString* readString = [[NSMutableString alloc] init]; 129 char readBuffer[1024]; 130 131 int br = 0; 132 NSLog(@"size of %li",sizeof(readBuffer)); 133 while((br = recv(sockfd, readBuffer, sizeof(readBuffer), 0)) < sizeof(readBuffer)) 134 { 135 NSLog(@"read datas length is :%d",br); 136 137 // [readString appendFormat:[NSString stringWithCString:readBuffer length:br]]; 138 [readString appendString:[NSString stringWithCString:readBuffer encoding:kCFStringEncodingUTF8]]; 139 140 NSLog(@"Hava received datas is :%@",readString); 141 } 142 143 close(sockfd); 144 }else { 145 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host " stringByAppendingString:hostName] message:@"Please check the hostname in the preferences." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 146 [alert show]; 147 //[alert release]; 148 } 149 150 /* 151 } 152 else 153 { 154 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Could not look up host " stringByAppendingString:hostName] message:@"Please check the hostname in the preferences." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil]; 155 [alert show]; 156 [alert release]; 157 } 158 **/ 159 } 160 161 - (void)Send:(id)sender 162 { 163 char message[7] = "aaag"; 164 send(sockfd,message,sizeof(message),0); 165 NSLog(@"%s",message); 166 } 167 168 // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. 169 - (void)viewDidLoad { 170 [self Connect:@"www.baidu.com" content:nil]; 171 172 [super viewDidLoad]; 173 174 NSLog(@"view has been loaded!"); 175 } 176 177 178 /* 179 // Override to allow orientations other than the default portrait orientation. 180 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 181 // Return YES for supported orientations 182 return (interfaceOrientation == UIInterfaceOrientationPortrait); 183 } 184 */ 185 186 - (void)didReceiveMemoryWarning { 187 // Releases the view if it doesn't have a superview. 188 [super didReceiveMemoryWarning]; 189 190 // Release any cached data, images, etc that aren't in use. 191 } 192 193 - (void)viewDidUnload { 194 // Release any retained subviews of the main view. 195 // e.g. self.myOutlet = nil; 196 } 197 198 199 200 @end