网络:交换机,路由器,网线
交换机:分配..
路由器:找寻网络线路
网络架构: 应用层 ---> 表示层 ---> 会话层 ---> 传输层 ---> 网络层 ---> 数据链路层 ----> 物理层
TCP/IP 商用: 应用层 ---> 传输层 ---> 网络层 ---> 物理+数据链路
socket 在传输层和应用层之间
TCP/IP 传输流程:
一次连接三次握手:客服端访问服务器端,服务器端响应,服务器访问客户端,客户端响应
套接字之间的连接过程可以分为三个步骤:服务器监听,客户端请求,连接确认。
//服务器端
#import "AppDelegate.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
@interface AppDelegate (){
//服务器标志
int server_flag;
//客户端标志
int client_flag;
//地址
struct sockaddr_in addr;
}
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 错误
int error = -1;
#pragma mark --- 服务器端设置 ---
//创建服务器端 (IP类型,通信协议, )
server_flag = socket(AF_INET, SOCK_STREAM, 0);
//将服务器绑定到一个具体的计算机
//端口
addr.sin_port = htons(9006);
//计算机
addr.sin_addr.s_addr = INADDR_ANY;
//IPV4
addr.sin_family = AF_INET;
//server_flag 绑定
error = bind(server_flag, (struct sockaddr*)&addr, sizeof(addr));
//最大连接数
error = listen(server_flag, 100);
printf("服务器启动成功!\n");
//等待
while (YES) {
//等待接收
client_flag = accept(server_flag, NULL, NULL);
//保存接收数据
//字符数组
char buff[1024] = {0};
//接收数据长度
long length = 0;
length = recv(client_flag, buff, 1024, 0);
buff[length] = '\0';
printf("client asy : %s \n",buff);
//发送数据
send(client_flag, "hello world", 80, 0);
close(server_flag);
}
return YES;
}
//客户端
#import "AppDelegate.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
@interface AppDelegate ()
{
int client_flag ;
struct sockaddr_in server;
}
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
int error = -1;
client_flag = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_port = htons(9006);
server.sin_addr.s_addr = inet_addr("172.18.16.158");
error = connect(client_flag, (struct sockaddr*)&server, sizeof(server));
send(client_flag, "鲁二蛋", 1024, 0);
char buff[1024] = {0};
long length = 0;
length = recv(client_flag, buff, 1024, 0);
buff[length] = '\0';
printf("server say : %s\n",buff);
// close(client_flag);
return YES;
}