Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5954073
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T17:55:06+00:00 2026-05-22T17:55:06+00:00

NEW SIMPLER VERSION OF PROBLEM: I’m trying to connect to and communicate with a

  • 0

NEW SIMPLER VERSION OF PROBLEM:

I’m trying to connect to and communicate with a Bonjour device using an Objective-C client and I’m having trouble resolving the service (server). Originally I tried to do a more complicated example, but I found the basic socket connection even with port/ip specified wasn’t working.

I have the most barebones possible code using the cocoaAsyncSocket library:

AsyncSocket *xxx = [[[AsyncSocket alloc] initWithDelegate:self] autorelease];
NSError **err;
[xxx connectToHost: @"localhost" onPort: 5000 error: err];
NSLog(@"err=%@",err);

And here’s the server I’m trying to connect to (Python script):

# TCP server with bonjour broadcast!    
import select
import sys
import pybonjour
import socket
from time import sleep

#name    = sys.argv[1]
#regtype = sys.argv[2]
#port    = int(sys.argv[3])

# Bonjour service parameters
name = "TEST"
regtype = "_xxx._tcp."
port = 5000
# Tcp socket stuff
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind(("", port))
server_socket.listen(5)


def register_callback(sdRef, flags, errorCode, name, regtype, domain):
    if errorCode == pybonjour.kDNSServiceErr_NoError:
        print 'Registered service:'
        print '  name    =', name
        print '  regtype =', regtype
        print '  domain  =', domain

sdRef = pybonjour.DNSServiceRegister(name = name,
                                     regtype = regtype,
                                     port = port,
                                     callBack = register_callback)


# register bonjour service
print "Registering Bonjour service"
ready = select.select([sdRef], [], [])
print "ready=",ready
if sdRef in ready[0]:
    pybonjour.DNSServiceProcessResult(sdRef)

def configLoop():
    data = "Entering configuration mode"
    client_socket.send (data)
    data = "1) Network SSID: "
    client_socket.send (data)
    ssid = client_socket.recv(512)
    print "Network SSID:",ssid
    data = "2) Login: "
    client_socket.send (data)
    login = client_socket.recv(512)
    print "Login:",login
    data = "3) Password: "
    client_socket.send (data)
    passw = client_socket.recv(512)
    print "Password:",passw
    data = "Restarting server and attempting to connect to "+ssid
    client_socket.send (data)
    sleep(1)
    sys.exit(0)



print "TCPServer Waiting for client on port",port
try:
    while 1:

        client_socket, address = server_socket.accept()
        print "I got a connection from ", address

        data = "connection!"
        client_socket.send (data)

        while 1:
            data = client_socket.recv(512)
            if ( data == 'q' or data == 'Q'):
                client_socket.close()
                break;
            elif (data == 'C' or data == 'config'): # Enter configuration mode
                configLoop();
            else:
                print "RECIEVED:" , data

finally:
    sdRef.close()

The server never sees an incoming connection. On the client side, the error var has the value or something- nothing what I’d expect. Help please?

OLD (more complicated version, uses the same server):

My debug output basically says the service is resolved… and then I get a socket disconnect immediately after. Meanwhile my server sits there and hasn’t seen incoming connections.

I’ve walked through with the debugger when I get the initial connection and print out the name of the service- and then it hangs until I press continue and then I get a socket disconnect immediately after???

I’m very new to Objective-C and event driven programming, so perhaps I’m handling something wrong? I appreciate any advice!

Client (Debugger) output:

Running…
2011-05-10 14:10:26.822 Client[34709:a0f] TEST
2011-05-10 14:10:26.850 Client[34709:a0f] Socket disconnected
2011-05-10 14:10:29.724 Client[34709:a0f] Could not resolve: {
    NSNetServicesErrorCode = -72003;
    NSNetServicesErrorDomain = 10;
} 

Server output:

Registering Bonjour service
ready= ([<DNSServiceRef object at 0x100583290>], [], [])
Registered service:
  name    = TEST
  regtype = _xxx._tcp.
  domain  = local.
TCPServer Waiting for client on port 5000

The client code (ClientController.m, basically lifted from http://www.macresearch.org/cocoa-scientists-part-xxix-message):

#import "ClientController.h"
#import "AsyncSocket.h"


@interface ClientController ()

@property (readwrite, retain) NSNetServiceBrowser *browser;
@property (readwrite, retain) NSMutableArray *services;
@property (readwrite, assign) BOOL isConnected;
@property (readwrite, retain) NSNetService *connectedService;
@property (readwrite, retain) MTMessageBroker *messageBroker;

@end


@implementation ClientController

@synthesize browser;
@synthesize services;
@synthesize isConnected;
@synthesize connectedService;
@synthesize socket;
@synthesize messageBroker;

-(void)awakeFromNib {
    services = [NSMutableArray new];
    self.browser = [[NSNetServiceBrowser new] autorelease];
    self.browser.delegate = self;
    self.isConnected = NO;
}

-(void)dealloc {
    self.connectedService = nil;
    self.browser = nil;
    self.socket = nil;
    self.messageBroker = nil;
    [services release];
    [super dealloc];
}

-(IBAction)search:(id)sender {
    [self.browser searchForServicesOfType:@"_xxx._tcp." inDomain:@""];
}

-(IBAction)connect:(id)sender {
    NSNetService *remoteService = servicesController.selectedObjects.lastObject;
    remoteService.delegate = self;
    [remoteService resolveWithTimeout:30];
    NSLog(@"%@",remoteService.name);
}

-(IBAction)send:(id)sender {
    NSData *data = [textView.string dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(textView.string);
    // Use socket to send raw text data once connected
}

#pragma mark AsyncSocket Delegate Methods
-(void)onSocketDidDisconnect:(AsyncSocket *)sock {
    NSLog(@"Socket disconnected");
}

-(BOOL)onSocketWillConnect:(AsyncSocket *)sock {
    if ( messageBroker == nil ) {
        [sock retain];
        return YES;
    }
    return NO;
}

-(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port {      
    //MTMessageBroker *newBroker = [[[MTMessageBroker alloc] initWithAsyncSocket:socket] autorelease];
    //[sock release];
    //newBroker.delegate = self;
    //self.messageBroker = newBroker;
    self.isConnected = YES;
}

#pragma mark Net Service Browser Delegate Methods
-(void)netServiceBrowser:(NSNetServiceBrowser *)aBrowser didFindService:(NSNetService *)aService moreComing:(BOOL)more {
    [servicesController addObject:aService];
}

-(void)netServiceBrowser:(NSNetServiceBrowser *)aBrowser didRemoveService:(NSNetService *)aService moreComing:(BOOL)more {
    [servicesController removeObject:aService];
    if ( aService == self.connectedService ) self.isConnected = NO;
}

-(void)netServiceDidResolveAddress:(NSNetService *)service {
    NSError *error;
    self.connectedService = service;
    self.socket = [[[AsyncSocket alloc] initWithDelegate:self] autorelease];
    [self.socket connectToAddress:service.addresses.lastObject error:&error];
}

-(void)netService:(NSNetService *)service didNotResolve:(NSDictionary *)errorDict {
    NSLog(@"Could not resolve: %@", errorDict);
}

@end
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T17:55:07+00:00Added an answer on May 22, 2026 at 5:55 pm

    I am having the same issue. It seems the problem is that a connection is already in place : “Attempting to connect while connected or accepting connections. Disconnect first”. Unfortunately i haven’t been able to resolve it yet. Any idea ? It might a delay or ordering process problem.

    EDIT :
    Actually, changing connectToAddress to ConnectToHost made it for me ! 🙂

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to Flex SDK and trying to implement a simple project using Doug
Relatively new to rails and trying to model a very simple family tree with
I'm new to postgreSQL and I have a simple question: I'm trying to create
I was trying to make a tail-recursive version of this very simple SML function:
The new ASP.NET routing is great for simple path style URL's but if you
I am making a simple game in order to learn a new language. I
I there a simple way to append a new field to an existing open
This is an incredibly simple question (I'm new to Python). I basically want a
I've written a simple multi-threaded game server in python that creates a new thread
I have a simple application with the following code: FileInfo[] files = (new DirectoryInfo(initialDirectory)).GetFiles();

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.