Reputation: 10503
I'm trying to setup a listenerSocket on localhost using GCDAsyncSocket
for iOS device.
In the socketDidDisconnect
delegate I either get error Code=49 for trying with port 0 (which I'm hoping would find the first available free port).
Or if I use a port no then I get error Code=61 for trying to connect with localhost
.
- (IBAction)start:(id)sender {
asyncSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *err = nil;
if(![asyncSocket connectToHost:@"localhost" onPort:0 error:&err])
{
NSLog(@"Connect Error: %@", err);
}
}
#pragma mark – delegate
-(void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(NSError *)err
{
NSLog(@"socketDidDisconnect");
if (err) {
NSLog(@"Socket Error: %@", err);
// Error in connect function:
// NSPOSIXErrorDomain Code=49 "Can't assign requested address" - onPort:0
// NSPOSIXErrorDomain Code=61 "Connection refused" - connectToHost:@"localhost"
}
}
Upvotes: 2
Views: 1042
Reputation: 122391
connectToHost
will act as the client-side of the connection. You want to read the Writing a server section of the help page:
listenSocket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error = nil;
if (![listenSocket acceptOnPort:port error:&error])
{
NSLog(@"I goofed: %@", error);
}
- (void)socket:(GCDAsyncSocket *)sender didAcceptNewSocket:(GCDAsyncSocket *)newSocket
{
// The "sender" parameter is the listenSocket we created.
// The "newSocket" is a new instance of GCDAsyncSocket.
// It represents the accepted incoming client connection.
// Do server stuff with newSocket...
}
However you need to know the port to use (if you let the system decide what port to use then how is a client supposed to know how to connect to the server?). Also the port will almost certainly need to be > 1024
(out of the reserved port range). However I haven't ever tried to create a Server on iOS.
Upvotes: 1