Objective c: Send audio data in rtp packet via socket - objective-c

In my app, I have to capture microphone and send audio data in rtp packet. But I only see receive rtp data like iOS RTP live audio receiving or unanswered one.
I used following code with AsuncUdpSocket to sent audio data but it wasn't wrap in rtp packet. Is there any library to wrap my audio data into rtp packet?
initial AsyncUdpSocket:
udpSender = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error;
[udpSender connectToHost:#"192.168.1.29" onPort:1024 error:&error];
I send audio data in my playback callback function:
static OSStatus playbackCallback(void *inRefCon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData) {
/**
This is the reference to the object who owns the callback.
*/
AudioProcessor *audioProcessor = (AudioProcessor*) inRefCon;
// iterate over incoming stream an copy to output stream
for (int i=0; i < ioData->mNumberBuffers; i++) {
AudioBuffer buffer = ioData->mBuffers[i];
// find minimum size
UInt32 size = min(buffer.mDataByteSize, [audioProcessor audioBuffer].mDataByteSize);
// copy buffer to audio buffer which gets played after function return
memcpy(buffer.mData, [audioProcessor audioBuffer].mData, size);
// set data size
buffer.mDataByteSize = size;
//Send data to remote server
NSMutableData *data=[[NSMutableData alloc] init];
Float32 *frame = (Float32*)buffer.mData;
[data appendBytes:frame length:size];
if ([udpSender isConnected])
{
[udpSender sendData:data withTimeout:-1 tag:1];
}
}
return noErr;
}
How do I accomplish this?
Thanks.

Finally, here's my solution.
Setup the microphone capture process:
-(void)open {
NSError *error;
m_capture = [[AVCaptureSession alloc]init];
AVCaptureDevice *audioDev = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
if (audioDev == nil)
{
printf("Couldn't create audio capture device");
return ;
}
//m_capture.sessionPreset = AVCaptureSessionPresetLow;
// create mic device
AVCaptureDeviceInput *audioIn = [AVCaptureDeviceInput deviceInputWithDevice:audioDev error:&error];
if (error != nil)
{
printf("Couldn't create audio input");
return ;
}
// add mic device in capture object
if ([m_capture canAddInput:audioIn] == NO)
{
printf("Couldn't add audio input");
return ;
}
[m_capture addInput:audioIn];
// export audio data
AVCaptureAudioDataOutput *audioOutput = [[AVCaptureAudioDataOutput alloc] init];
[audioOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
if ([m_capture canAddOutput:audioOutput] == NO)
{
printf("Couldn't add audio output");
return ;
}
[m_capture addOutput:audioOutput];
[audioOutput connectionWithMediaType:AVMediaTypeAudio];
[m_capture startRunning];
return ;
}
Capture the microphone data:
-(void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
char szBuf[450];
int nSize = sizeof(szBuf);
if (isConnect == YES)
{
if ([self encoderAAC:sampleBuffer aacData:szBuf aacLen:&nSize] == YES)
{
[self sendAudioData:szBuf len:nSize channel:0];
}
}
Initial the socket
-(void)initialSocket{
//Use socket
printf("initialSocket\n");
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
NSString *ip = #"192.168.1.147"; //Your IP Address
uint *port = 22133;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)ip, port, &readStream, &writeStream);
if (readStream && writeStream) {
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
iStream = (__bridge NSInputStream *)readStream;
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];
oStream = (__bridge NSOutputStream *)writeStream;
[oStream setDelegate:self];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream open];
}
}
Send data to socket when capture the data form microphone.
-(void)sendAudioData: (char *)buffer len:(int)len channel:(UInt32)channel
{
Float32 *frame = (Float32*)buffer;
[globalData appendBytes:frame length:len];
if (isConnect == YES)
{
if ([oStream streamStatus] == NSStreamStatusOpen)
{
[oStream write:globalData.mutableBytes maxLength:globalData.length];
globalData = [[NSMutableData alloc] init];
}
}
}
Hope this will help someone.

Related

Objective c - Writing image file to ip address

Experts:
I've been researching all morning on how to write an image file to another computer via IP Address. Do I really need to create sockets, set delegates, schedule a run loop, check space available, and all that hoopla? Really? Can't I just save the file to a URL using the IP Address and default port?
I'm asking this question because I'm not making much progress on my own and I know the minute I hit Post Your Question I'll find some useful information. But in case that does not happen, please reply. Any help is appreciated.
This is the code I have and I think I'm on the wrong track:
#import "TESTtcpController.h"
#interface TESTtcpController()
#property (nonatomic, strong)NSInputStream *inputStream;
#property (nonatomic, strong)NSOutputStream *outputStream;
//void CFStreamCreatePairWithSocketToHost (
// CFAllocatorRef alloc,
// CFStringRef host,
// UInt32 port,
// CFReadStreamRef *readStream,
// CFWriteStreamRef *writeStream
// );
#end
#implementation TESTtcpController
+ (void)sendFile:(UIImage *)image
{
UInt32 port = 80;
NSString *ipAddress = #"10.10.10.10";
TESTtcpController *tcpController = [[TESTtcpController alloc] init];
[tcpController connect:port ipAddress:ipAddress];
[tcpController postFile:image];
[tcpController disconnect];
tcpController = nil;
}
-(void)connect:(UInt32)port ipAddress:(NSString *)ipAddress
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ipAddress, port, &readStream, &writeStream);
self.inputStream = (__bridge NSInputStream *)readStream;
self.outputStream = (__bridge NSOutputStream *)writeStream;
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
NSLog(#"input stream id %#", self.inputStream);
/* Store a reference to the input and output streams so that
they don't go away.... */
}
- (void)postFile:(UIImage *)image
{
}
- (void)dataSending:(NSString*)data {
if(self.outputStream) {
if(![self.outputStream hasSpaceAvailable])
return;
NSData *_data=[data dataUsingEncoding:NSUTF8StringEncoding]; int data_len = [_data length];
uint8_t *readBytes = (uint8_t *)[_data bytes];
int byteIndex=0;
unsigned int len=0;
while (TRUE) {
len = ((data_len - byteIndex >= 40960) ? 40960 : (data_len-byteIndex));
if(len==0)
break;
uint8_t buf[len]; (void)memcpy(buf, readBytes, len);
len = [self.outputStream write:(const uint8_t *)buf maxLength:len]; byteIndex += len;
readBytes += len; }
}
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
switch(eventCode) {
case NSStreamEventNone:
break;
case NSStreamEventOpenCompleted:
break;
case NSStreamEventHasBytesAvailable:
break;
case NSStreamEventHasSpaceAvailable:
// {
// uint8_t *readBytes = (uint8_t *)[_data mutableBytes];
// readBytes += byteIndex; // instance variable to move pointer
// int data_len = [_data length];
// unsigned int len = ((data_len - byteIndex >= 1024) ?
// 1024 : (data_len-byteIndex));
// uint8_t buf[len];
// (void)memcpy(buf, readBytes, len);
// len = [stream write:(const uint8_t *)buf maxLength:len];
// byteIndex += len;
// break;
// }
case NSStreamEventErrorOccurred:
break;
case NSStreamEventEndEncountered:
break;
// continued ...
}
}
-(void)disconnect{
NSLog(#"disconnect method called");
NSStreamStatus socketStatus = [self.outputStream streamStatus];
int status = socketStatus;
NSLog(#"Stream Status is %i", status);
if (status == 2) {
[self.inputStream close];
[self.outputStream close];
NSLog(#"Socket Closed");
}
}
- (void)deallocMe
{
[TESTtcpController dealloc];
}
#end
You should use the AFNetworking library. Image uploads will be trivial. Read about AFNetworking here: http://cocoadocs.org/docsets/AFNetworking/2.0.0/
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

NSInputStream not opening stream/ How to post data when setting up stream

What I am trying to do: I have a url request (post) where I send some information to a api server which then starts streaming data in bytes to me.
1) How do I post data when trying to set up a stream as right now I am just using a url, can I incorporate a NSURLRequest some how?
2) Why isnt my stream even opening (streamStatus returns 0) and thus - (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode never being called? , this is my best attempt and for the most part following this Guide
- (void)setUpStreamFromURL:(NSURL *)path {
// iStream is NSInputStream instance variable
iStream = [[NSInputStream alloc] initWithURL:path];
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[iStream open];
NSLog(#"Stream Open: %lu",[iStream streamStatus]); //return 0
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
NSLog(#"Streaming");
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
if(!_data) {
_data = [[NSMutableData data] init];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:1024];
if(len) {
[_data appendBytes:(const void *)buf length:len];
NSLog(#"DATA BEING SENT : %#", _data);
// bytesRead is an instance variable of type NSNumber.
// [bytesRead setIntValue:[bytesRead intValue]+len]; //getting error that setInt value is not part of NSNumber, and thats true so not sure what to do about it, but this isn't the issue.
} else {
NSLog(#"no buffer!");
}
break;
}
case NSStreamEventEndEncountered:
{
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
stream = nil; // stream is ivar, so reinit it
break;
}
// continued ...
}
}
also incase it helps, my header file:
#import <Foundation/Foundation.h>
#import "Login.h"
#interface Stream : NSStream <NSStreamDelegate> {
NSMutableArray *searchIdList;
NSInputStream *iStream;
NSNumber *bytesRead;
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode ;
-(id)initWithLoginObject:(Login *)log;
#property NSMutableData *data;
#end
You can't use NSURLRequest in Stream.
To create a request you can use this.
request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("POST"),(CFURLRef) url, kCFHTTPVersion1_1);
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("User-Agent"), CFSTR("MSControl-US"));
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Content-Type"), CFSTR("application/json"));
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Connection"), CFSTR("Keep-Alive"));
After that you can create the stream using
readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request)
or if you already have an opened stream you can serialize your request With :
NSData *data = (NSData *)CFHTTPMessageCopySerializedMessage(request);
and send with This:
length = [data length];
CFWriteStreamWrite((CFWriteStreamRef)outStream,data,lenght);
Hope this help

cant read data from tcp port

i have written code for reading data from tcp port 3000
- (BOOL)connect
{
int cIter = 0;
while(cIter++<5)
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
#try{
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)M_CONNECT_HOST, M_CONNECT_PORT, &readStream, &writeStream);
}
#catch (NSException *ex) {
}
if(readStream!=nil && writeStream!=nil)
{
m_sin = (__bridge NSInputStream *)readStream;
m_sout = (__bridge NSOutputStream *)writeStream;
[m_sin setDelegate:self];
[m_sout setDelegate:self];
[m_sin scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[m_sout scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[m_sin open];
[m_sout open];
return true;
}
}
return false;
}
When i write to tcp output stream its working but when i try to read from the tcp input stream its not reading i mean my
[m_sin read:t maxlength:10];
is always returning -1 (where m_sin is my input stream)
And i m passing the data to the tcp port by terminal
please Help me
Implement the handleEvent and check it out the eventCode
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode{
switch (eventCode) {
case NSStreamEventOpenCompleted:
NSLog(#"stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (aStream == inputStream) {
// read it in
unsigned int len = 0;
len = [inputStream read:buf maxLength:1019];
buf[len] = '\0';
if(!len) {
if ([aStream streamStatus] != NSStreamStatusAtEnd){
NSLog(#"Failed reading data from peer");
}
} else {
//I am reading UIImage here
NSData *data = [NSData dataWithBytes:(const void *)buf length:1019];
UIImage *image = [UIImage imageWithData:data];
self.transferedimage.image = image;
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(#"stream ErrorOccurred");
break;
case NSStreamEventEndEncountered:
NSLog(#"stream EndEncountered");
break;
default:
NSLog(#"stream UnKnown");
break;
}
}

NSJSONSerialization error

I'm trying to send json object to server. But I received an error and I can't fix it.
-(void) connectToHost{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"localhost", 9123, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open]; }
This is my connection to host.
NSDictionary *setUser = [NSDictionary
dictionaryWithObjectsAndKeys:[#"u" stringByAppendingString:my.id],#"id",
#"GET_USER_INFO",#"command",
#"",#"value",
nil];
NSArray *array = [NSArray arrayWithObject:setUser];
jsonDataToSendTheServer = [array JSONRepresentation];
NSLog(#" %# ", jsonDataToSendTheServer);
// array = [NSArray arrayWithObject:jsonDataToSendTheServer];
NSLog(#" %# ", array);
NSLog(#"true or false %c",[NSJSONSerialization
isValidJSONObject: array]);
bytesWritten = [NSJSONSerialization writeJSONObject:array toStream:outputStream options:NSJSONWritingPrettyPrinted error:nil];
and this part is NSJSONSerialization part.
However I got an error.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '***+[NSJSONSerialization writeJSONObject:toStream:options:error:]: stream is not open for writing'
I'm new at objective-c. I can't fix the problem for 3 hours.
=======================================
edit:
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(#"stream event %i", streamEvent); //this doesn't post in the log when stream opened...
NSLog(#"bytes %i",bytesWritten);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];
if (nil != output) {
NSLog(#"server said: %#", output);
//[self messageReceived:output];
}
}
}
}
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//[theStream release];
theStream = nil;
break;
case NSStreamEventHasSpaceAvailable:
{
uint8_t *readBytes = (uint8_t *)[_data mutableBytes];
readBytes += bytesWritten; // instance variable to move pointer
int data_len = [_data length];
unsigned int len = ((data_len - bytesWritten >= 1024) ?
1024 : (data_len-bytesWritten));
uint8_t buf[len];
(void)memcpy(buf, readBytes, len);
//len = [theStream write:(const uint8_t *)buf maxLength:len];
NSLog(#"written %s", buf );
bytesWritten += len;
}
break;
case NSStreamEventErrorOccurred:
{
NSLog(#"no connection");
}
case NSStreamEventNone:
{
//printf("EVENT: None.\n");
break;
}
default:
NSLog(#"Unknown event");
}}
this is my stream: handleEvent: function.
Now after I did add the connectionToHost to delegate I get this kind of error.
012-08-10 16:14:27.302 TaraftarlikOyunu[2274:c07] written P∏◊P‡ˇø
2012-08-10 16:14:28.399 TaraftarlikOyunu[2274:c07] benim bu id 587127341
2012-08-10 16:14:28.399 TaraftarlikOyunu[2274:c07] benim ad Ahmet
2012-08-10 16:14:28.400 TaraftarlikOyunu[2274:c07]
[{"id":"u581277341","command":"GET_USER_INFO","value":""}]
2012-08-10 16:14:28.404 TaraftarlikOyunu[2274:c07] stream event 4
2012-08-10 16:14:28.404 TaraftarlikOyunu[2274:c07] bytes 86
(lldb)
now I don't have an idea that if it buffered or not
=======================EDIT2===============
sorry about this.
the problem probably appears because of this
(void)memcpy(buf, readBytes, len);
I just copy and paste this part of code.
what may be the problem!
The connection method you are using is a little much.
You need to make sure the connection has happened in the delegate
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventHasSpaceAvailable:
NSLog(#\"None!\");
break;
case NSStreamEventOpenCompleted:
NSLog(#\"Stream opened\");
//NOW you can write to the stream

How do i know if my client iOS app is connected to the server?

I press the button to connect to the server (TCP), but i don't know whether it connected or not..
Here is that part of the code:
[self connectToServerUsingCFStream:msg portNo:50000];
if(readStream && writeStream)
{
NSString *newText = [[NSString alloc] initWithFormat:#"Connected!! :)"];
statusText.text = newText;
[newText release];
pingButton.hidden = NO;
}
else
{
NSString *newText = [[NSString alloc] initWithFormat:#"Connection unsuccessful :("];
statusText.text = newText;
[newText release];
}
I always get the "Connected!! :)" even if the server is offline :s
The solution for people following the connection method:
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault,
(CFStringRef) urlStr,
portNo,
&readStream,
&writeStream);
if (readStream && writeStream)
{
CFReadStreamSetProperty(readStream,
kCFStreamPropertyShouldCloseNativeSocket,
kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream,
kCFStreamPropertyShouldCloseNativeSocket,
kCFBooleanTrue);
iStream = (NSInputStream *)readStream;
[iStream retain];
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[iStream open];
oStream = (NSOutputStream *)writeStream;
[oStream retain];
[oStream setDelegate:self];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[oStream open];
}
is using the
-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
like this:
-(void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
NSString *io;
if (theStream == iStream) io = #">>";
else io = #"<<";
NSString *event;
switch (streamEvent)
{
case NSStreamEventNone:
event = #"NSStreamEventNone";
statusText.text = #"Can not connect to the host!";
break;
case NSStreamEventOpenCompleted:
event = #"NSStreamEventOpenCompleted";
pingButton.hidden = NO;
statusText.text = #"Connected";
break;
case NSStreamEventHasBytesAvailable:
event = #"NSStreamEventHasBytesAvailable";
if (theStream == iStream)
{
//read data
uint8_t buffer[1024];
int len;
while ([iStream hasBytesAvailable])
{
len = [iStream read:buffer maxLength:sizeof(buffer)];
if (len > 0)
{
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
NSData *theData = [[NSData alloc] initWithBytes:buffer length:len];
if (nil != output)
{
//do something with data
}
}
}
}
break;
case NSStreamEventHasSpaceAvailable:
event = #"NSStreamEventHasSpaceAvailable";
if (theStream == oStream)
{
//send data
uint8_t buffer[11] = "I send this";
int len;
len = [oStream write:buffer maxLength:sizeof(buffer)];
if (len > 0)
{
NSLog(#"Command send");
[oStream close];
}
}
break;
case NSStreamEventErrorOccurred:
event = #"NSStreamEventErrorOccurred";
statusText.text = #"Can not connect to the host!";
pingButton.hidden = YES;
break;
case NSStreamEventEndEncountered:
event = #"NSStreamEventEndEncountered";
statusText.text = #"Connection closed by the server.";
pingButton.hidden = YES;
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[theStream release];
theStream = nil;
break;
default:
event = #"** Unknown";
}
NSLog(#"%# : %#", io, event);
}
(for all I know!) The credits go to deksa from this post (though i don't know who was the creator, because i've seen this some times on the web, including here o SO). This code was slightly modified by me (pingButton, statusText), if you want the original one go to the link previously mentioned.
The Apple Developer Site has some info on this as well.
Like i've said, I had seen some stuff looking like this on the web, but now i understand that everything that happens after you connect is "automatic"; for instance, if the server is on hold with a read(), the case NSStreamEventHasSpaceAvailable: will be called automatically, and all the code in there will be run.
Now I consider this question answered.
Although you did not provide enough informations, I'd suggest to use ASIHTTPRequest for HTTP, and AsyncSocket for TCP and UDP. If an connection was established, callback methods will be triggered,
I have to say, that my experiences with CFNetwork are very limited, but for me it seems, as if you are just testing, if stream objects exists (if(readStream && writeStream)).
A quick look at CFNetwork Programming Guide: Working with Read Streams tells me, that you have to open it with CFReadStreamOpen(), this function will return an boolean, if it really did open the stream.
if (!CFReadStreamOpen(myReadStream)) {
CFStreamError myErr = CFReadStreamGetError(myReadStream);
// An error has occurred.
if (myErr.domain == kCFStreamErrorDomainPOSIX) {
// Interpret myErr.error as a UNIX errno.
} else if (myErr.domain == kCFStreamErrorDomainMacOSStatus) {
// Interpret myErr.error as a MacOS error code.
OSStatus macError = (OSStatus)myErr.error;
// Check other error domains.
}
}
BTW:
instead of
NSString *newText = [[NSString alloc] initWithFormat:#"Connected!! :)"];
statusText.text = newText;
[newText release];
you just can write statusText.text = #"Connected!! :)";