我对Objective-C非常陌生,我想在我正在开发的iOS应用程序和我的Python3套接字服务器(可以工作)之间进行通信。问题是我不知道如何在Objective-C中使用套接字,也不知道在Xcode8中安装库时从哪里开始。现在我只希望能够将数据发送到服务器,并在iOS设备上接收返回的响应。我看过sys.socket.h,但我还是不知道如何使用它,任何帮助都将不胜感激。
谢谢!
发布于 2016-11-25 10:27:27
几年前,我使用了SocketRocket。我从我的旧项目中发布了它的一些代码。我不知道这是否仍然有效,但您可能会有使用它的想法。
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"); }
[wsmain send:commands];
通过发送命令,您将收到didReceiveMessage
方法的响应。
发布于 2016-11-25 10:30:27
你看到https://github.com/robbiehanson/CocoaAsyncSocket了吗?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);
}
委派
-(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");
}
}
发布于 2016-11-26 12:43:20
另一个选择是socket.io。它有用Swift编写的服务器库和iOS客户端库。它的API是相当广泛的。
https://stackoverflow.com/questions/40799923
复制