#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
//1 连接
- (BOOL)connect:(NSString *)ip port:(int)port{
//1 创建socket
int clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
self.clientSocket = clientSocket;
//2 连接到服务器
struct sockaddr_in serverAdd;
serverAdd.sin_family = AF_INET;
serverAdd.sin_port = htons(port); //16位 底8位 高8位 高8位 低8位
serverAdd.sin_addr.s_addr = inet_addr(ip.UTF8String) ;
int result = connect(clientSocket, (const struct sockaddr *)&serverAdd, sizeof(serverAdd));
if (result == 0) {
NSLog(@"成功");
return YES;
}else{
NSLog(@"失败");
return NO;
}
}
//2 发送http请求和接收http响应
- (NSString *)sendAndRec:(NSString *)request{
//3 发数据
// 第一个参数指定发送端套接字描述符;
// 第二个参数指明一个存放应用程式要发送数据的缓冲区;
// 第三个参数指明实际要发送的数据的字符数;
// 第四个参数一般置0。
//返回实际发送的字节个数
const char *msg = request.UTF8String;
//发送失败 返回-1
//strlen 获取的是字符个数 sizeof获取的是字节数
ssize_t sendLen = send(self.clientSocket, msg, strlen(msg), 0);
NSLog(@"发送的字节个数:%zd",sendLen);
//4 接收数据
char buffer[1024];
//等待服务器返回数据 阻塞
ssize_t recvLen = -1;
//循环接收所有的数据
NSMutableData *mData = [NSMutableData data];
while (recvLen != 0) {
recvLen = recv(self.clientSocket, buffer, sizeof(buffer), 0);
// NSLog(@"接收到得字节个数:%zd",recvLen);
NSData *data = [NSData dataWithBytes:buffer length:recvLen];
[mData appendData:data];
}
//把字节数组转换成字符串
NSString *str = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];
// NSString *str = [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
return str;
}
//3 关闭
- (void)close{
//5 关闭
close(self.clientSocket);
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
//1 发送和接收数据
//2 发送什么数据 ,接收的是什么数据 (http的请求和响应)
//http协议中要求
//http协议中的长连接和短连接
//短连接 请求结束后会立即断开
//长连接 当请求结束后,等等待非常短的时间, 如果超过时间没有请求,断开连接
//http请求协议
//请求行
//请求头
//请求体
if ([self connect:@"119.75.218.70" port:80]) {
//发送http请求
NSString *request = @"GET / HTTP/1.0\r\n"
@"Host: www.baidu.com\r\n"
@"User-Agent:Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4\r\n"
@"Connection: close\r\n"
@"\r\n";
NSString *response = [self sendAndRec:request];
NSLog(@"%@",response);
//处理响应的结果
//根据分析的http响应报文. 要通过两个\r\n截取响应体
//1 找到两个\r\n的位置
NSRange range = [response rangeOfString:@"\r\n\r\n"];
//2 从两个\r\n之后开始截取,截取到的最后
NSString *html = [response substringFromIndex:range.location + range.length];
[self.webView loadHTMLString:html baseURL:[NSURL URLWithString:@"http://www.baidu.com"]];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end