iOS 用C 创建TCP链接

#import "ChatC.h"
#import 
#import 
#import 
@implementation ChatC

/// 套接字
static int fd;
- (void)buildClient{
    /* 在终端 用命令 man socket 查看socket函数的用法及其参数的含义
     AF_INET :ipv4
     AF_INET6 : ipv6
     SOCK_STREAM TCP
     SOCK_DGRAM  UDP
     SOCK_RAW    超级用户
     */
    // 1.1. 建立socket
    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd == -1){
        NSLog(@"socket fail");
    }
    // 1.2. 连接服务器
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    /// 地址
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    /// 端口
    addr.sin_port = htons(8888);
    int result = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
    if (result == -1){
        NSLog(@"connect fail");
    }
    /// 1.3. 发送数据
    [self sendData:@"sdd"];
    /// 1.4循环接收数据
    [NSThread detachNewThreadSelector:@selector(threadRecvData) toTarget:self withObject:nil];
}
- (void)threadRecvData{
    char buf[32];
    while (1) {
        /// 等待缓存区满了才不阻塞
        ssize_t result = recv(fd, buf, 32, MSG_WAITALL);
        if (result <= 0){
            NSLog(@"recv fail!");
            break;
        }
        buf[result] = 0;
        NSLog(@"%s",buf);
    }
    close(fd);
}
/// 在终端开启socket: nc -l 8888
- (void)sendData:(NSString *)content{
    [NSThread detachNewThreadSelector:@selector(threadSendData:) toTarget:self withObject:content];
}
- (void)threadSendData:(NSString *)content{
    const char * contC = [content UTF8String];
    size_t res = send(fd, contC, strlen(contC), 0);
    if (res < 0){
        NSLog(@"send fail");
    }
}
@end

你可能感兴趣的:(iOS 用C 创建TCP链接)