实现效果
-
1.查找WebView
-
2.拖动WebView到ViewController
-
3.导入库
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
-
4.请求数据
#import "ViewController.h"
#import <sys/socket.h>
#import <netinet/in.h>
#import <arpa/inet.h>
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (nonatomic, assign) int clientSocket;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//1 连接百度的服务器
BOOL result = [self content:@"119.75.216.20" port:80];
if (!result) {
NSLog(@"NO");
return;
}else {
NSLog(@"YES");
}
//构造http请求头
NSString *request = @"GET / HTTP/1.1\r\n"
"Host: www.baidu.com\r\n\r\n"
"User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1";
//服务器返回的响应 响应体
NSString *respose = [self sendAndRecv:request];
NSLog(@"---%@",respose);
//关闭连接 http协议要求,请求结束后要关闭连接
close(self.clientSocket);
//找到\r\n\r\n!
// NSRange rang = [respose rangeOfString:@"\r\n\r\n"];
//从\r\n\r\n之后的第一个位置开始截取字符串 响应体
// NSString *html = [respose substringFromIndex:rang.length + rang.location];
// [self.webView loadHTMLString:respose baseURL:[NSURL URLWithString:@"http://www.baidu.com"]];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.baidu.com"]]];
}
//1.连接服务器
-(BOOL)content:(NSString *)ip port:(int)port {
int clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
self.clientSocket = clientSocket;
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ip.UTF8String);
addr.sin_port = htons(port);
int result = connect(clientSocket, (const struct sockaddr *)&addr, sizeof(addr));
if (result == 0) {
return YES;
}else {
return NO;
}
}
//2.发送和接收数据
-(NSString *)sendAndRecv:(NSString *)sendMsg{
//3 向服务器发送数据
//成功则返回实际参数,失败返回1
const char *msg = sendMsg.UTF8String;
ssize_t sendCount = send(self.clientSocket, msg, strlen(msg), 0);
NSLog(@"发送的字节数 %zd",sendCount);
//4 接收服务器返回的数据
//返回的是实际接收的字节数
uint8_t buffer[1024];
NSMutableData *mData = [NSMutableData data];
ssize_t recvCount = recv(self.clientSocket, buffer, sizeof(buffer), 0);
[mData appendBytes:buffer length:recvCount];
//服务器返回多次数据,等所有的数据都接收完成,再转换成字符串
while (recvCount != 0) {
recvCount = recv(self.clientSocket, buffer, sizeof(buffer), 0);
NSLog(@"接收的字节数 %zd",recvCount);
[mData appendBytes:buffer length:recvCount];
}
//把字节数组转换成字符串
NSString *recvMsg = [[NSString alloc]initWithData:mData.copy encoding:NSUTF8StringEncoding];
return recvMsg;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end