[英]Objective-C Sockets Send and Receive on iOS
我是Objective-C的新手,并且想在我正在使用的iOS应用程序和Python 3套接字服务器(可以工作)之间进行通信。 问题是我不知道如何在Objective-C中使用套接字,也不知道在Xcode 8中安装库时从哪里开始。现在,我只想能够将数据发送到服务器并收到响应在iOS设备上。 我已经看过sys.socket.h了,但是再次,我不知道如何使用它,任何帮助将不胜感激。
谢谢!
几年前,我使用了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
方法中收到响应。
你见过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");
}
}
另一个选项是socket.io 。 它具有用Swift编写的服务器库和iOS客户端库。 它的API相当广泛。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.