ios socket笔记

//第一步导入头

#import 
#import 
#import 


/**
 *连接到服务器
 */

- (BOOL)connectToHost:(NSString *)host port:(int)port{

    //第一个参数 dimain,协议簇 制定iPv4
    //第二个参数 type , socket的类型,流socket,数据包socket
    //第三个参数 protocol 协议
    
    //返回值 如果创建成功 返回socket的描述符,失败返回-1
    
    self.clientSocket = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in serverAddress;
    serverAddress.sin_family = AF_INET;
    
    //连接服务器 connect(int,const struct sockaddr*,socklen_t)
    //第一个参数 socket描述符
    //第二个参数 结构体 ip地址跟端口
    //第三个参数 结构体长度 sizeof
    //返回值 成功 0 失败 非0
    
    //addr.sin_family = AF_INET;
    //addr.sin_port = htons(port);
    //addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    
    serverAddress.sin_addr.s_addr = inet_addr(host.UTF8String);
    serverAddress.sin_port = htons(port);
    return (connect(self.clientSocket, (const struct sockaddr *)&serverAddress, sizeof(serverAddress)) == 0);
}


/**
 *发送跟接收
 */
- (NSString *)sendAndRecv:(NSString *)message{
    //成功返回实际传送出去的字符数,失败返回-1;
    const char *msg = (message.UTF8String);
    ssize_t sendLen = send(self.clientSocket,msg,strlen(msg),0);
    NSLog(@"发送字节数 %zd",sendLen);
    uint8_t buffer[1024];
    
    //返回时实际接受的字节字数

    NSMutableData *mdata = [NSMutableData data];
    ssize_t recvLen = recv(self.clientSocket,buffer,sizeof(buffer),0);

    [mdata appendBytes:buffer length:recvLen];
    //服务器返回多次数据,等所有数据接收完成,再转换成字符串
    while (recvLen != 0) {
        recvLen = recv(self.clientSocket,buffer,sizeof(buffer),0);
        NSLog(@"接收字节数 %zd",recvLen);
        [mdata appendBytes:buffer length:recvLen];

    }
    NSString *str = [[NSString alloc]initWithData:mdata.copy encoding:NSUTF8StringEncoding];
    
    
//
//    NSString *str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    return str;
    
    
}

/**
 *断开连接
 */

- (void)disconnection{
    close(self.clientSocket);
}

主要是有以上三个函数来实现socket开启,传输接收数据以及关闭socket

你可能感兴趣的:(ios socket笔记)