objective-c - Xcode : How to add Protocol to a socket Connection and send JSON data

标签 objective-c json sockets

我是 Xcode 的新手,我正在关注 this github 示例。我的任务是连接到信令服务器。如果设置了协议(protocol),信令服务器只接受连接。

  • 有没有办法可以将协议(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/

    相关文章:

    objective-c - cocoa 窗口拖动

    objective-c - 混合两个图像并从两个 UIImageViews 绘制调整大小的图像

    javascript - MongoDB 脚本加载正确,但不工作

    java - 如何使用java优先在两台没有外网IP的机器之间建立套接字连接?

    c++ - 在完成端口调用 WSASend()?

    linux - 预 fork 服务器的套接字调用的正确顺序

    ios - 在ios中刷新tableviewcontroller

    iphone - 来自多个方法的 NSURLConnection 请求 - 获取启动方法的回调

    json - 在 Go 中使用匿名成员展平编码的 JSON 结构

    json - 使用jq依次解析并显示一个json中的多个字段