I have been working with Apple's Network Framework to implement a WebSocket Client. Here is the receive block for my code:
nw_connection_receive(connection, 1, UINT32_MAX, ^(dispatch_data_t content, nw_content_context_t context, bool is_complete, nw_error_t receive_error) {
nw_retain(context);
nw_protocol_metadata_t wsMetadata = nw_content_context_copy_protocol_metadata(context,nw_protocol_copy_ws_definition());
nw_ws_opcode_t inputOpCode = nw_ws_metadata_get_opcode(wsMetadata);
fprintf(stderr,"\n\nInput Opcode: %d\n", inputOpCode);
dispatch_block_t schedule_next_receive = ^{
// If the context is marked as complete, and is the final context,
// we're read-closed.
if (is_complete &&
(context == NULL || nw_content_context_get_is_final(context))) {
exit(0);
}
// If there was no error in receiving, request more data
if (receive_error == NULL) {
receive_loop(connection);
}
nw_release(context);
};
if (content != NULL) {
// If there is content, write it to stdout asynchronously
schedule_next_receive = Block_copy(schedule_next_receive);
dispatch_write(STDOUT_FILENO, content,dispatch_get_main_queue(), ^(__unused dispatch_data_t _Nullable data, int stdout_error) {
if (stdout_error != 0) {
errno = stdout_error;
fprintf(stderr,"stdout write error\n");
} else {
schedule_next_receive();
}
Block_release(schedule_next_receive);
});
} else {
// Content was NULL, so directly schedule the next receive
schedule_next_receive();
}
});
This code block is taken from (Implementing netcat with Network Framework | Apple Developer Documentation). I now want to get rid of the dispatch_write block and convert the received dispatch_data_t object to a string representation either a CFStringRef or a C++ std::string.