簡體   English   中英

iOS上的Objective-C套接字發送和接收

[英]Objective-C Sockets Send and Receive on iOS

我是Objective-C的新手,並且想在我正在使用的iOS應用程序和Python 3套接字服務器(可以工作)之間進行通信。 問題是我不知道如何在Objective-C中使用套接字,也不知道在Xcode 8中安裝庫時從哪里開始。現在,我只想能夠將數據發送到服務器並收到響應在iOS設備上。 我已經看過sys.socket.h了,但是再次,我不知道如何使用它,任何幫助將不勝感激。

謝謝!

幾年前,我使用了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];

  1. 委托方法

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

  1. 發送命令

    [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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM