NSStream Handle Event Giving Status 4 - objective-c

I was trying on a TCP connection app, and I am getting a NSStreamEvent "4" on handleEvent. What am I doing wrong?
My code is like,
-(void) initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"localhost", 80, &readStream, &writeStream);
inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
- (IBAction)didTapButton:(id)sender {
NSString *response = inputTextField.text;
NSLog(#"%#", response);
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
NSLog(#"Stream has bytes available");
break;
case NSStreamEventErrorOccurred:
NSLog(#"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
NSLog(#"Stream closed");
break;
default:
NSLog(#"Unknown event: %# : %d", theStream, streamEvent);
}
}
The console gives,
2012-05-29 13:37:07.132 GestureTrial[24289:f803] Stream opened
2012-05-29 13:37:07.133 GestureTrial[24289:f803] Stream opened
2012-05-29 13:37:07.133 GestureTrial[24289:f803] Unknown event: <__NSCFOutputStream: 0x6b85c70> : 4
when tried to send a message to server. I tried it with a tcp tester app for Mac, and it's working fine, so might not be a firewall issue. The output is same for device as well as simulator. Any help would be much appreciated.

Actually you're not doing anything wrong.
This event (it is NSStreamEventHasSpaceAvailable) usually occours after writing to the stream telling you that stream is ready for writing again and after opening a writable stream. Please refer to NSStream Class Reference or, to be exact: Stream Event Constants.
If you're not familliar to << operator, it means shift bits to left for n places (each shift equals to multiplying by 2). Translation would be:
typedef enum {
NSStreamEventNone = 0,
NSStreamEventOpenCompleted = 1,
NSStreamEventHasBytesAvailable = 2,
NSStreamEventHasSpaceAvailable = 4,
NSStreamEventErrorOccurred = 8,
NSStreamEventEndEncountered = 16
};
In many applications you will se this event simply ignored (not handled) because it usually occours very soon after writing to the stream. If something goes wrong you get NSStreamEventErrorOccurred or NSStreamEventEndEncountered and these are the ones you need to handle. You could use NSStreamEventHasSpaceAvailable as a flag that it is o.k. to send some more data.
You should also know that both streams (inputStream and outputStream) are calling the same delegate method. That's why you get two NSStreamEventOpenCompleted events to begin with. But again in many cases this shouldnt be a problem. You can always check which stream is the originator of the event if needed.

Related

socket communication at separate thread

I already read 40 pages about threading, but still not sure about my case.
I have an NSObject, that open a socket connection to a device. This Object handle all the communication, sending and receiving messages and so on. I would like, that this stuff works on separate thread. I tried something like this:
- (IBAction)connect:(id)sender {
SocketConnectionController *sock = [SocketConnectionController new];
[[sock initWithParams:ip.text :port.text.intValue] performSelectorInBackground:#selector(initWithParams::) withObject:nil];
[[SocketConnectionController sharedInstance] sendCommand:GET_ID_STRING];
}
As you see, I am sending some message by using the existing instance of SocketConnectionController, but it doesn't send anything. There maybe some leak of understanding my side. I am sure, that the connection is open because of flashing lights on device. Am I creating the thread on the right way? If so, how can I use it now?
1. UPDATE:
I tried something like this:
NSOperationQueue* queue = [NSOperationQueue new];
SocketConnection *sock = [SocketConnection new];
[queue addOperation:sock];
but at the CPU graph I see, that the stuff still running on Thread 1 (mainThread).
What am I doing wrong?
2. UPDATE
I found out, that the run loop, that I need for the Input and Output Stream still running on the main Thread.
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
That's why the code of 1. Update don't work. So I need to create a new Thread and then a new run loop for this thread. That can not be done automatically by Cocoa-Framework like in the code before (performSelectorInBackground).
I found the way to perform the socket connection on the separate thread:
NSThread * nThread;
- (NSThread *)networkThread {
nThread = nil;
nThread =
[[NSThread alloc] initWithTarget:self
selector:#selector(networkThreadMain:)
object:nil];
[nThread start];
NSLog(#"thread: %#, debug description: %#", nThread, nThread.debugDescription);
return nThread;
}
- (void)networkThreadMain:(id)unused {
do {
[[NSRunLoop currentRunLoop] run];
} while (YES);
}
- (void)scheduleInCurrentThread:(id)unused
{
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSRunLoopCommonModes];
}
-(BOOL) connectWithError:(NSString **) e
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"127.0.0.1", [server port], &readStream, &writeStream);
inputStream = (__bridge NSInputStream *) readStream;
outputStream = (__bridge NSOutputStream *) writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[self performSelector:#selector(scheduleInCurrentThread:)
onThread:[self networkThread]
withObject:nil
waitUntilDone:YES];
[inputStream open];
[outputStream open];
}
All you need is to input this code in the new class of type NSThread.

NSOutputStream crashing with Bad Access after write (Objective-c)

I have been trying to get a basic TCP client up and running for my iOS application but have run into a block which i cannot seem to work my head around.
So far i can connect, send a message which is received on the server side but then my app crashes.
Client.h
#import <Foundation/Foundation.h>
#interface Client : NSObject <NSStreamDelegate>
{
NSInputStream *inputStream;
NSOutputStream *outputStream;
}
-(void)initNetworkCommunication;
-(void)send:(NSString*)message;
#end
Client.m
#import "Client.h"
#implementation Client
- (void)initNetworkCommunication {
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"10.0.1.51", 7769, &readStream, &writeStream);
inputStream = ( NSInputStream *)CFBridgingRelease(readStream);
outputStream = ( NSOutputStream *)CFBridgingRelease(writeStream);
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
- (void)send:(NSString*)message
{
NSData *data = [[NSData alloc] initWithData:[message dataUsingEncoding:NSUTF8StringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
}
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(#"stream event %i", streamEvent);
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:NSASCIIStringEncoding];
if (nil != output) {
NSLog(#"server said: %#", output);
}
}
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(#"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
NSLog(#"End Encountered!");
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
theStream = nil;
break;
default:
NSLog(#"Unknown event");
}
}
#end
The output in the console is
2013-10-03 17:01:38.542 MMORPG[6076:70b] stream event 1
2013-10-03 17:01:38.543 MMORPG[6076:70b] Stream opened
2013-10-03 17:01:43.495 MMORPG[6076:70b] stream event 4
2013-10-03 17:01:43.495 MMORPG[6076:70b] Unknown event
It seems like, my message is sent, i receive stream event #4 and then i get a bad access crash. The problem is i have no idea what its having trouble accessing?
Any help would be greatly appreciated!
The problem is that NSStream keeps an assign/unsafe_unretained reference to its delegate. If the delegate is released before the stream is closed and released, the stream will try to call methods on its now deallocated delegate, causing a crash. The solution is to either make sure some other object has a strong reference to the client, preventing its early deallocation, or else make sure you close and release the stream before its delegate is deallocated.

Socket check TCP/IP connection exists and shorten timeout

I am trying to connect my iOS application to a printer on a adhoc network, I need to check the connection is open and valid before sending anything to the printer, How can I achieve this? currently I am doing the following
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
readStream = NULL;
writeStream = NULL;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)IPADDRESS, NUM_PORT,NULL ,&writeStream );
if(writeStream)
{
//inputStream = (__bridge NSInputStream *)readStream;
oStream = (__bridge NSOutputStream *)writeStream;
//[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//[iStream setDelegate:delegate];
[oStream setDelegate:delegate];
//[iStream open];
[oStream open];
}
and
int bytesWritten;
int bytesTotal = [data length];
bytesWritten = [oStream write:[data bytes] maxLength: bytesTotal];
NSLog(#"Bytes Written To Printer : %d",bytesWritten);
but it is always going in and writeStream is never null so I am unable to stop it trying to push data to the socket.
~Edit - Maybe I'm best rephrasing my question, How can I stop it from hanging for 30+ seconds until it realises there is no connection?
I need to check the connection is open and valid before sending anything to the printer, How can I achieve this?
By sending something to the printer. The only way to detect a connection problem in TCP is to do some I/O with it.

more outputstream problems...raw data and odd output. what did i do wrong?

I've opened the following input and output bluetooth streams using Apple's External Accessory Framework:
session = [[EASession alloc] initWithAccessory:acc forProtocol:protocol];
if (session){
[[session inputStream] setDelegate:self];
[[session inputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session inputStream] open];
[[session outputStream] setDelegate:self];
[[session outputStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[[session outputStream] open];
}
I'm writing to it like this:
uint8_t aByte[] = {0x02, 0x06, 0x04};
[[session outputStream] write:aByte maxLength:4];
NSLog(#"%d", aByte[2]);
I'm reading from it like this:
case NSStreamEventHasBytesAvailable:
NSLog(#"NSStreamEventHasBytesAvailable");
uint8_t readBuf[128];
memset(readBuf, 0, sizeof(readBuf));
NSInteger numberRead = [[session inputStream] read:readBuf maxLength:3];
if(numberRead < 0){
NSError *error = [[session inputStream] streamError];
NSLog(#"%#", [error localizedDescription]);
}
else if (numberRead > 0) {
NSLog(#"numberRead: %d", numberRead);
NSLog(#"readBuf: %s", readBuf);
}
else{
break;
}
break;
I SHOULD be receiving back from the device "AA4" because it's sends me back two alpha characters followed by the 3 byte that was sent to it in the last stream event. The LCD screen on the device is reporting that it has received a 2 a 4 and a 6. And it is reporting that it sent an A and A and a 4. But "NSLog(#"readBuf: %s", readBuf);" always prints:
AA + a upside question mark//(can't seem to copy and paste that symbol from xcode)
Anyone have any ideas on what I've done wrong?
Thanks!
Nevermind...
I printed each byte individually instead of as a string. Printed the first two as char's and the last as a decimal. C style output is still weird to me...

NSInputStream does not call Delegate (stream:handleEvent:)

I searched the web for a long time...I didn't find an answer for my issue, so I decided to post here.
I try to establish a connection to a NNTP-server using NSStream.
In a test-program, I open the streams and send a message. The delegate-method (stream:handleEvent:) is called twice for the output-stream (NSStreamEventOpenCompleted, NSStreamEventHasSpaceAvailable) but never for the input-stream!
Why does the input stream never call the delegate? Any ideas?
Basically, the code looks like this:
init and open streams:
CFReadStreamRef tmpiStream;
CFWriteStreamRef tmpoStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)SERVER, PORT, &tmpiStream, &tmpoStream);
iStream = (__bridge NSInputStream *) tmpiStream;
oStream = (__bridge NSOutputStream *)tmpoStream;
[iStream setDelegate:self];
[oStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];
[oStream open];
send message:
NSData *data = [[NSData alloc] initWithData:[messageString dataUsingEncoding:NSASCIIStringEncoding]];
[oStream write:[data bytes] maxLength:[data length]];
receive messages:
-(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
NSLog(#"EventCode: %i", eventCode);
//switch-case-statement...(using constants - NSStreamEventOpenCompleted...)
}
The class which contains that code inherits from NSObjects and implements NSStreamDelegate.
(iOS5 with ARC)
Thx for any help!
EDIT:
I just tried "polling" after opening streams like this - it's working:
while (![iStream hasBytesAvailable])
{}
uint8_t buffer[1024];
int len;
NSString *str = #"";
while ([iStream hasBytesAvailable])
{
len = [iStream read:buffer maxLength:sizeof(buffer)];
if (len > 0)
{
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSISOLatin1StringEncoding];
if (output != nil)
{
str = [str stringByAppendingString:output];
}
}
}
NSLog(#"Response: %#", str);
But, for sure, I still need a better (async) solution ;)
I found your answer here, I have the same issue. Your answer worked for me, but I think this works better:
How to use delegate in NSStream?
To quote him:
The run loop isn't running long enough for the delegate method to be
called.
Add:
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];
right after you open the stream. This is only necessary in a program
without a GUI -- otherwise the run loop would be spun for you.
So mine looks like this:
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:30.0]];
Edited:
Then when you have the data, for example I have all my data complete when NSStreamEventEndEncountered occurs in the delegate method stream:handleEvent I put this:
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
CFRunLoopStop(CFRunLoopGetCurrent());
[theStream close];
Which closes the run loop before the 30.0s or however long you set it. It would be the same to your answer if your code was in NSStreamHasBytesAvailable.
This allows me to still use the delegate methods and keep the run loop open until the download is completed, without skipping the delegate method all together.
Are you letting the run loop run in the default mode?
Try checking the input stream status (-streamStatus).
Is anything logged to the console?
You claim the delegate method is called for the output stream, but your NSLog() call doesn't log the stream. Are you sure?
Finally, this is unrelated, but you should be using a __bridge_transfer cast if you mean to transfer ownership of the owned Core Foundation stream objects to ARC. Even better, use CFBridgingRelease() since that has an obvious symmetry with the Create in the function name. Unless there are CFRelease() calls which you didn't show, then the existing code is leaking those streams.
I had this same issue and then I realized that I accidentally called
[iStream setDelegate:self]
before I created iStream.