Scoket 简单实现通信原理
直接代码 Scoket服务器端代码
#import "AppDelegate.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
@interface AppDelegate ()
{
int server_flag;
int client_flag;
struct sockaddr_in addr;
}
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
server_flag = socket(AF_INET, SOCK_STREAM, 0);
addr.sin_port = htons(9007);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
int error = -1;
error = bind(server_flag, (struct sockaddr *)&addr, sizeof(addr));
error = listen(server_flag, 80);
while (1) {
client_flag = accept(server_flag,NULL,NULL);
send(client_flag, "Hello,Lanou!", 100, 0);
char buff[1024];
long length = 0;
length = recv(client_flag, buff, 1024, 0);
buff[length] = '\0';
printf("client say:%s",buff);
}
return YES;
}
直接代码 Scoket客户端代码
#import "AppDelegate.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
@interface AppDelegate ()
{
struct sockaddr_in server;
int client_flag;
}
@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(9007);
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];
long length = 0;
length = recv(client_flag, buff, 1024, 0);
buff[length] = '\0';
printf("server say:%s",buff);
return YES;
}
