【OC】基于CocoaAsyncSocket创建的简单SocketDemo

效果图:

IP:服务器端的地址

PORT: 端口,可以设置为任意一个

代码:

服务器端连接:

        int port = [_txf_PORT.stringValue intValue];
        
        if (port < 0 || port > 65535)
        {
            [_txf_PORT setStringValue:@""];
            port = 0;
        }
        NSString *ip = _txf_IP.stringValue;
        NSError *error = nil;
        NSLog(@"%@", _txf_IP.stringValue);
        NSLog(@"%d", port);
        if(![listenSocket acceptOnInterface:ip port:port error:&error])
        {
            [self logError:FORMAT(@"Error starting server: %@", error)];
            return;
        }
        
        [self logInfo:FORMAT(@"Echo server started on port %hu", [listenSocket localPort])];

 服务器端的连接成功返回:

- (void)socket:(GCDAsyncSocket *)sock didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
    // This method is executed on the socketQueue (not the main thread)
    
    @synchronized(connectedSockets)
    {
        [connectedSockets addObject:newSocket];
    }
    
    NSString *host = [newSocket connectedHost];
    UInt16 port = [newSocket connectedPort];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        @autoreleasepool {
        
            [self logInfo:FORMAT(@"Accepted client %@:%hu", host, port)];
        
        }
    });
    
    NSString *welcomeMsg = @"Welcome to the AsyncSocket Echo Server\r\n";
    NSData *welcomeData = [welcomeMsg dataUsingEncoding:NSUTF8StringEncoding];
    
    [newSocket writeData:welcomeData withTimeout:-1 tag:WELCOME_MSG];
    
    [newSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:READ_TIMEOUT tag:0];
}

 服务器端获取数据:

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    // This method is executed on the socketQueue (not the main thread)
    
    dispatch_async(dispatch_get_main_queue(), ^{
        @autoreleasepool {
        
            NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length] - 2)];
            NSString *msg = [[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding];
            if (msg)
            {
                [self logMessage:msg];
            }
            else
            {
                [self logError:@"Error converting received data into UTF-8 String"];
            }
        
        }
    });
    
    // Echo message back to client
    [sock writeData:data withTimeout:-1 tag:ECHO_MSG];
}

客户端连接:

            socketQueue = dispatch_queue_create("socketQueue", NULL);
            sendSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:socketQueue];

            NSError *error;
            
            isConnect = [sendSocket connectToHost:_txf_IP.stringValue onPort:[_txf_PORT.stringValue intValue] error: &error];
            
            if (!isConnect)
            {
                NSLog(@"connect error: %@", error);
                return;
            }

客户端发送数据:

- (IBAction)btn_SendData:(id)sender {
    NSData* data = [[NSString stringWithFormat:@"%@\r\n", _text_Content.string] dataUsingEncoding: NSUTF8StringEncoding];
   
    if (isConnect) {
        [sendSocket writeData: data withTimeout: -1 tag: 0];
    }
}

源码地址:SocketDemo

基于CocoaAsyncSocket创建的简单SocketDemo例子-Swift文档类资源-CSDN文库

基于CocoaAsyncSocket:CocoaAsyncSocket    (有兴趣的可以深入研究)

CocoaAsyncSocket-Swift文档类资源-CSDN文库

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

三岁牧羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值