简体   繁体   中英

Objective-C Sockets Send and Receive on iOS

I'm very new to Objective-C and would like to communicate between an iOS app which I'm working on and my Python 3 socket server (which works). The problem is I don't know how to use sockets in Objective-C and don't know where to start when installing libraries in Xcode 8. For now I just want to be able to send data to the server and receive a response back on the iOS device. I have seen sys.socket.h but again, I don't know how to use it, any help would be much appreciated.

Thanks!

Few years ago I used SocketRocket . I am posting some of the code of it from my old project. I don't know if that still works but you might get the idea of using it.

  1. Connecting to server

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];

  1. Delegate Methods

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

  1. Sending Commands

    [wsmain send:commands];

By sending commands, you will receive a response in didReceiveMessage method.

have you seen https://github.com/robbiehanson/CocoaAsyncSocket ? It's easy to use socket

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);
}

delegate

-(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");
}

}

Another option is socket.io . It has server libraries and a iOS client library written in Swift. It's API is quite extensive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM