GCDAsyncSocket readData not being called
I am trying to send a message to a server and get a response using my iPhone. I can connect to the server using:
telnet 123.123.123.1 6000
Trying 123.123.123.1...
Connected to 123.123.123.1.
Escape character is '^]'.
?VERSION
OK
VERSION=PROTOCOL: 1.1.0
? VERSION is my question
OK states that he received and understood the question
VERSION = response from server
so i am trying to do the same but with xcode
So I have this in my view DidLoad
dispatch_queue_t mainQueue = dispatch_get_main_queue();
asyncSocket = [[GCDAsyncSocket alloc]initWithDelegate:self delegateQueue:mainQueue];
asyncSocket.delegate = self;
NSString *host = @"123.123.123.1";
uint16_t port = 6000;
NSLog(@"Connecting to \"%@\" on port %hu...", host, port);
NSError *error = nil;
if (![asyncSocket connectToHost:host onPort:port withTimeout:5.0 error:&error])
{
NSLog(@"Error connecting: %@", error);
}
else
{
NSLog(@"Connecting...");
}
And I have the following code showing that it is connected
-(void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:
(UInt16)port
{
NSLog(@"socket:%p didConnectToHost:%@ port:%hu", sock, host, port);
// We're just going to send a test string to the server.
NSString *myStr = @"?VERSION";
NSData *myData2 = [myStr dataUsingEncoding:NSUTF8StringEncoding];
[asyncSocket writeData:myData2 withTimeout:-1 tag:0];
}
And the next to show it is written
-(void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag{
NSLog(@"WRITING");
[asyncSocket readDataToData:[GCDAsyncSocket LFData] withTimeout:-1 tag:0];
}
Unfortunately it is never called
- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
NSString *tempString = [[NSString alloc]initWithData:data
encoding: NSUTF8StringEncoding];
}
I'm lost and really need help
source to share
This is because you are writing and reading at the same time. Call first [asyncSocket writeData:myData2 withTimeout:-1 tag:0];
and didWriteDataWithTag
call at [asyncSocket readDataToData:[GCDAsyncSocket LFData] withTimeout:-1 tag:0];
. You are on the same thread - dispatch_get_main_queue()
- it cannot do two things at the same time.
source to share