基于网络通信
iOS
socket技术
`#include <sys/socket.h> `
`#include <netinet/in.h`
@implementation AppDelegate
{
//服务端的标识
int server_flag;
//客户端的标识
NSMutableArray *clients;
//计算机地址
struct sockaddr_in addr;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
clients = [NSMutableArray array];
int error = -1;
//服务端
//1.创建服务端的标识符(int)
server_flag = socket(AF_INET, SOCK_STREAM, 0);
//2.将服务端的标识符,绑定到一个具体的计算机(ip,port)里 sockaddr_in
addr.sin_port = htons(10000);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
error = bind(server_flag, (struct sockaddr *)&addr, sizeof(addr));
//3.服务端要做好能同时处理多少个链接的事情
error = listen(server_flag, 100);
//4.服务端做好等待客户端链接请求的准备
while (1)
{
//5.将收到的客户端链接请求生成一个标志位,作为某个客户端的标识
int client_flag = accept(server_flag, NULL, NULL);
[clients addObject:@(client_flag)];
//6.通过客户端的标志位进行消息传输
char buff[1024];
int length = recv(client_flag, buff, sizeof(buff), 0);
buff[length] = '\0';
printf("client say:%s\n",buff);
//发送消息...
char message[] = "Hello, c!\n";
send([clients.lastObject intValue], message, sizeof(message), 0);
//7.关闭取消链接的客户端标志位
// close(client_flag);
}
return YES;
}
客户端和服务器端配置基本相同,不同的地方已经注释说明
@implementation AppDelegate
{
struct sockaddr_in server;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
int error = -1;
//设置客服端表示
int client_flag = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
//服务器端端口号
server.sin_port = htons(10000);
//服务器端ip
server.sin_addr.s_addr = inet_addr("172.18.16.37");
//链接服务器
error = connect(client_flag, (struct sockaddr *)&server, sizeof(server));
//发送消息
send(client_flag, "nong sha lei", 80, -1);
char buff[1024];
int length = recv(client_flag, buff, 1024, -1);
buff[length] = '\0';
printf("server say:%s\n",buff);
close(client_flag);
return YES;
}