Reputation: 2789
I am learning iOS network programming from this tutorial. I tried modifying the code so that a response is sent to the server immediately after a connection is successful. The only part of the code I change is in this function. The problem is that the app stalls and nothing happens on the line [outputStream write:[data bytes] maxLength:[data length]];
Thus NSLog(@"sent test");
does not get executed. What am I doing wrong?
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(@"stream event %i", streamEvent);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
//my code
if (theStream == outputStream) {
NSLog(@"outputStream");
NSData* data = [NSData dataWithBytes:@"test" length:4];
[outputStream write:[data bytes] maxLength:[data length]];
NSLog(@"sent test");
} //end my code
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
//...
}
}
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[theStream release];
theStream = nil;
break;
default:
NSLog(@"Unknown event");
}
}
EDIT: solution found here How to use NSOutputStream's write message?
Upvotes: 3
Views: 5127
Reputation: 1885
ok while i was working with raw socket connections i have used that code to send data to server. it might be helpful to you
if (theStream == outputStream) {
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];//str is my string to send
int byteIndex = 0;
uint8_t *readBytes = (uint8_t *)[data bytes];
readBytes += byteIndex; // instance variable to move pointer
int data_len = [data length];
// NSLog(@"%i",[data length]);
unsigned int len = ((data_len - byteIndex >= 1024) ?
1024 : (data_len-byteIndex));
uint8_t buf[len];
(void)memcpy(buf, readBytes, len);
len = [outputStream write:(const uint8_t *)buf maxLength:len];
byteIndex += len;
}
Upvotes: 1