scoket 实现百度页面的两种方式:
1.利用系统自带
//1.创建URL
NSURL *url=[NSURL URLWithString:@"http://m.baidu.com"];
//2.创建请求
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[request setValue:@"iPhone AppleWebKit" forHTTPHeaderField:@"User-Agent"];
//3.发送
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *html=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
[self.webView loadHTMLString:html baseURL:url];
}];
2.利用socket
- (void)viewDidLoad {
[super viewDidLoad];
if ([self connectWith:@"61.135.185.17" withHton:80]) {
NSLog(@"error");
return;
}
NSLog(@"OK");
NSString *request=@"GET / HTTP/1.1\r\n"
"Host: m.baidu.com\r\n"
"User-Agent: iPhone AppleWebKit\r\n"
"connection: Close\r\n\r\n";
NSString *result = [self sendAndRevi:request];
NSRange range=[result rangeOfString:@"\r\n\r\n"];
if (range.location !=NSNotFound) {
NSString *html=[result substringFromIndex:range.location];
[self.webView loadHTMLString:html baseURL:[NSURL URLWithString:@"m.baidu.com"]];
}
}
- (NSString *)sendAndRevi:(NSString *)request{
//注意:send的第三个值用strlen 不是sizeof
send(self.clientsocket, request.UTF8String, strlen(request.UTF8String), 0);
uint8_t buffer[1024];
ssize_t recvLen = -1;
NSMutableData *dataM = [NSMutableData data];
while (recvLen !=0) {
recvLen= recv(self.clientsocket, buffer, sizeof(buffer), 0);
[dataM appendBytes:buffer length:recvLen];
}
NSString *str = [[NSString alloc]initWithData:dataM encoding:NSUTF8StringEncoding];
return str;
}
- (BOOL)connectWith:(NSString *)addr withHton:(int)hton{
// 1.scoke
self.clientsocket = socket(AF_INET, SOCK_STREAM, 0);
// 2.connect;
struct sockaddr_in serverAddress;
serverAddress.sin_family=AF_INET;
serverAddress.sin_addr.s_addr=inet_addr(addr.UTF8String);//这个方法会是地址翻转,翻转后的地址为所请求的地址
serverAddress.sin_port=htons(hton);//根据IP地址查找端口
return connect(self.clientsocket, (const struct sockaddr *)&serverAddress, sizeof(serverAddress));
}
ps.这个是前两节所讲的概念进行实际的演练,如果有什么概念不懂的地方可以看下前两个博客的概念,如果还有的不懂的,可以留言,会在第一时间回复的