我是 Xcode 的新手,我正在关注 this github 示例。我的任务是连接到信令服务器。如果设置了协议(protocol),信令服务器只接受连接。
例如:
// create the NSURLRequest that will be sent as the handshake
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"wss://example.com"]];
// create the socket and assign delegate
self.socket = [PSWebSocket clientSocketWithRequest:request];
self.socket.delegate = self;
//Something I need to add
self.socket.addprotocol="Protocol";
2>我还需要将JSON数据发送到下面的服务器是我需要用Objective C编写的Android代码
JSONObject message = new JSONObject();
message.put("pc", 0);
message.put("message", "Bye");
socket.sendText(message.toString());
} catch (JSONException e) {
}
最佳答案
对于问题 #1,很遗憾,您使用的 PocketSocket 库似乎不支持子协议(protocol)。然而,一切并没有丢失,因为有一个 pull request来自想要添加该功能的人。您可以合并这些更改,或者只修改在请求中设置适当的传出 header 的单行代码:
[request setValue:[_protocols componentsJoinedByString:@","] forHTTPHeaderField:@"Sec-WebSocket-Protocol"];
对于问题 #2,有 NSJSONSerialization ,它允许您轻松地将 Objective-C NSDictionaries 和 NSArrays 转换为 JSON 对象:
NSDictionary *o = @{
@"a": @"Ayyyy",
@"b": @"Beee"
};
NSError *error;
NSData *d = [NSJSONSerialization dataWithJSONObject:o options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
NSLog(@"Error JSON-encoding object: %@", error);
} else {
NSString *s = [NSString stringWithUTF8String:[d bytes]];
NSLog(@"JSON:\n%@", s);
}
关于objective-c - Xcode : How to add Protocol to a socket Connection and send JSON data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36320557/