2016-11-25 128 views
0

我对Objective-C非常陌生,希望在我正在使用的iOS应用程序和我的Python 3套接字服务器(工作)之间进行通信。问题是我不知道如何在Objective-C中使用套接字,并且不知道在Xcode 8中安装库时从哪里开始。现在,我只是希望能够将数据发送到服务器并接收响应在iOS设备上。我已经看到了sys.socket.h,但是,我不知道如何使用它,任何帮助将不胜感激。Objective-C在iOS上发送和接收套接字

谢谢!

回答

0

几年前我用SocketRocket。我从我的旧项目发布它的一些代码。我不知道这是否仍然有效,但您可能会想到使用它。

  1. 连接到服务器

NSMutableURLRequest *pushServerRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"ws://192.168.1.1"]]; [pushServerRequest setValue:@"WebSocket" forHTTPHeaderField:@"Upgrade"]; [pushServerRequest setValue:@"Upgrade" forHTTPHeaderField:@"Connection"]; [pushServerRequest setValue:"somekey" forHTTPHeaderField:@"Sec-WebSocket-Protocol"]; SRWebSocket *wsmain = [[SRWebSocket alloc] initWithURLRequest:pushServerRequest]; //Declare this as a global variable in a header file wsmain.delegate=self; [wsmain open];

  • 委托方法
  • -(void)webSocket:(SRWebSocket *)webSocket didReceiveMessage:(id)message { NSLog(@"Message %@",message); } - (void)webSocketDidOpen:(SRWebSocket *)webSocket { NSLog(@"Connected"); }

  • Se nding命令

    [wsmain send:commands];

  • 通过发送命令,您将收到didReceiveMessage方法的响应。

    0

    你见过https://github.com/robbiehanson/CocoaAsyncSocket? 可以很容易地使用套接字

    NSString *host = @"10.70.0.22"; 
    int port = 1212; 
    
    _socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)]; 
    
    NSError *error = nil; 
    [_socket connectToHost:host onPort:port error:&error]; 
    if (error) { 
        NSLog(@"%@",error); 
    } 
    

    代表

    -(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{ 
    NSLog(@"success"); 
    } 
    -(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err{ 
    if (err) { 
        NSLog(@"error %@",err); 
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ 
         [self connectToServer]; 
        }); 
    }else{ 
        NSLog(@"disconnect"); 
    } 
    

    }

    +0

    好吧,我想我已经成功安装了库。如何在不需要代码页的情况下与我的python服务器进行通信,我只想在ViewController.m文件中为新的操作执行此操作。 谢谢! – Oliver

    +0

    在终端中运行.py ... – LazyOranger

    +0

    嗨,谢谢您的回复。最后,我使用Swift 3并使用了SwiftSockets,它现在可以在我的python服务器上很好地工作,并且可以将我需要的请求发送给 – Oliver

    0

    另一种选择是socket.io。它具有服务器库和用Swift编写的iOS客户端库。它的API非常广泛。