0

I have issues sending messages over socket using GCDAsyncSocket. I establish a connection and try to send a message to server, but message is being sent when application quits. I need a way to do it before. I tried [asyncSocket disconnect]; but it changed nothing... Please help. Here is part of my code:

NSError *err = nil;
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
if(![asyncSocket connectToHost:@"localhost" onPort:7777 error:&err]){
// If there was an error, it's likely something like "already connected" or "no delegate set"
    NSLog(@"I goofed: %@", err);
}
NSString *requestStr = @"<?xml version='1.0' encoding='UTF-8' standalone='yes' ?><root><service>1</service><type>1</type><userProperties><username>someusername</username></userProperties></root>";
NSData *requestData = [requestStr dataUsingEncoding:NSUTF8StringEncoding];

[asyncSocket writeData:requestData withTimeout:1.0 tag:0];

NSData *receivedData;
[asyncSocket readDataToData:receivedData withTimeout:2.0 tag:0];
NSString *httpResponse = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(@"%@",httpResponse);
iblagajic
  • 71
  • 2
  • 9
  • Also see my very similar, answered question: http://stackoverflow.com/questions/11998408/having-trouble-programming-streams – khaliq Aug 19 '12 at 07:27

1 Answers1

2

Your problem is in the "readDataToData:receivedData" - You're asking GCDAsyncSocket to Read Data until it finds "nothing" - receivedData is unknown. One normally uses something like

[asyncSocket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:-1 tag:0];

That will read until it gets a CR/LF combination to terminate the read. You could also read the header and determine the length of the data to be read.

You need to tell it when to return from the read (that's why you're getting nothing back). Also it's probably only returning to you when the application quits because the socket is getting closed when the app terminates.

ferdil
  • 1,259
  • 11
  • 24