I'm trying to "send to" and "receive from" on same GCDAsyncSocket object, but it return's error as Attempting to accept while connected or accepting connections. Disconnect first. while trying to initialising the object.
My Code :
-(instancetype)initWithHost:(NSString *)host port:(NSInteger)port userData:(NSDictionary *)userData delegate:(id<AKSenderSocketDelegate>)delegate
{
self = [super init];
if (self)
{
self.delegate = delegate;
self.senderSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
self.senderSocket.userData = userData;
NSError *err = nil;
//---- Sender
if (![self.senderSocket connectToHost:host onPort:port error:&err])
{
NSLog(@"Failed to connect: %@", err);
}
else
{
NSLog(@"Connected to :%@:%ld",host,(long)port);
}
//---- Listener
if (![self.senderSocket acceptOnPort:0 error:&err])
{
NSLog(@"Failed to open lintening port. :%@",err.localizedDescription);
}
else
{
NSLog(@"Listening to port :%hu and host :%@",self.senderSocket.localPort,self.senderSocket.localHost);
}
}
return self;
}
Please help!!
You're overcooking the pudding (grin). Once you've connected, you're ready to start communicating. There's no need for the accept message.
connectToHost:onPort:error:is like placing a phone call: you call, the other party picks up (because that other party has already made itself available withacceptOnPort:error:or its equivalent). Once the connection is made, you can read and write data over the same socket; sockets are bi-directional.So if you want to "place a call", use
connectToHost:onPort:error:. If instead you want to wait for the other party to place the call, useacceptOnPort:error:. Regardless of which side of the conversation is the "connecter" or the "accepter", both sides of the conversation can both send (write) and listen (read).