我主要针对客户端分享一下socket的简单网络通信
一、导入库文件 <arpa/inet.h> <netdb.h>
二、创建 socket
int _socket = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == _socket) {
//创建失败
} else {
//创建成功
}
三、获取 IP 地址
NNString *host = @"192.168.10.11";
struct hostent *remoteHostEnt = gethotsbyname( [host UTF8String] );
if (NULL == remoteHostEnt) {
clost(_socket); //无法解析服务器的主机名
}
struct in_addr *remoteInAddr = (struct in_addr *)remoteHostEnt -> h_addr_list[0];
四、设置 socket 参数
int port = 1004;
struct sockaddr_in socketParameters;
socketParameters.sin_family = AF_INET;
socketParameters.sin_addr = *remoteInAddr;
socketParameters.sin_port = htons(port);
五、连接 socket
int ret = connect(sockerFileDescriptor, (struct sockaddr *) & socketParameters, sizeof(socketParameters));
if (-1 == ret) {
close (_socket);//连接失败
}
六、发送数据
NSString *string = @”你好!“;
typedef struct
{
unsigned char sendData [10];
}sendInfo;
sendInfo *info = malloc(sizeof(info));
memset (info, 0, sizeof(sendInfo));
memcpy(info -> sendData, [string UTF8String], strlen([string UTF8String]));
long int result = send(_socket, info, sizeof(info), 0);
if (result == -1) {
//发送数据失败
} else{
//发送数据成功
}
七、接收数据
typedef struct
{
unsigned char receData [10];
}receInfo;
receInfo *rece = malloc(sizeof(receInfo));
memset(rece, 0, sizeof(receInfo));
while ( recv(_socket, rece, sizeof(rece),0) != -1) {
break;//接收到数据
}
八、断开连接
close (_socker);