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

  • SEARCH
  • Home
  • 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 6347193
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T21:10:00+00:00 2026-05-24T21:10:00+00:00

I’ve got a simple client & server application semi working with CocoaAsyncSocket. I can

  • 0

I’ve got a simple client & server application semi working with CocoaAsyncSocket. I can use the client to connect to the server, and can pass data back and forth between them and the delegate methods seem to fire correctly. My problem is that I can only send data back to a (AsyncSocket *) object that is passed to one of delegate methods. When accepting a connection I add the socket to an NSMutableArray, but later if I try to use the socket writing fails. So

[connectedSockets addObject:newSocket];
//then later
[[connectedSockets objectAtIndex:i] writeData:someData withTimeout:-1 tag:0];

doesn’t work. Code is below for server and client. The initial communication does work, but when my notification gets called no data is sent, even though the NSLog statement tests the socket in the array and gets the proper IP Address & port #:

Server:

- (id)init
{
    self = [super init];
    if (self) {
        listenSocket = [[AsyncSocket alloc] initWithDelegate:self];
        [listenSocket setRunLoopModes:[NSArray arrayWithObject:NSRunLoopCommonModes]];
        [listenSocket acceptOnPort:42381 error:nil];


        connectedSockets = [[NSMutableArray alloc] init];
        newNotificationDictArray = [[NSMutableArray alloc] init];
        updateNotificationDictArray = [[NSMutableArray alloc] init];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(newJobNotification:)
                                                     name:@"NewJob"
                                                   object:nil];
    }

    return self;

}

-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
    [connectedSockets removeObject:sock];
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
    [connectedSockets removeObject:sock];
}

- (void)onSocket:(AsyncSocket *)sock didAcceptNewSocket:(AsyncSocket *)newSocket
{
    [connectedSockets addObject:newSocket];
}


- (void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port
{
if ([newNotificationDictArray count] > 0) {
    NSMutableData *data = [[NSMutableData alloc] init];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
    [archiver encodeObject:newNotificationDictArray forKey:@"DictArray"];
    [archiver finishEncoding];
    [archiver release];
    [sock writeData:data withTimeout:-1 tag:0];
    [data release];
}

[sock readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
    [sock readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
[sock readDataWithTimeout:-1 tag:0];
}

-(void) newJobNotification: (NSNotification *) notification
{
NSDictionary *dict = [notification userInfo];
[newNotificationDictArray addObject:dict];
[updateNotificationDictArray addObject:dict];
NSMutableData *updateData = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:updateData];
[archiver encodeObject:updateNotificationDictArray forKey:@"DictArray"];
[archiver finishEncoding]
[updateNotificationDictArray removeAllObjects];
[archiver release];
NSLog(@"Attempting to write to %@:%i", [[connectedSockets objectAtIndex:0] connectedHost], [[connectedSockets objectAtIndex:0] connectedPort]) 
[[connectedSockets objectAtIndex:0] writeData:updateData withTimeout:-1 tag:0];
}

and then the client:

- (id)init
{
self = [super init];
if (self) {
    socket = [[AsyncSocket alloc] initWithDelegate:self];
}
return self;
}

-(void) connectToHost: (NSString *) address
{

}

-(BOOL)onSocketWillConnect:(AsyncSocket *)sock 
{
[sock retain];
[socket readDataWithTimeout:-1 tag:0];
return YES;
}

-(void)onSocket:(AsyncSocket *)sock didConnectToHost:(NSString *)host port:(UInt16)port 
{    
NSLog(@"Did Connect on port %i", [sock connectedPort]);
}

-(void) disconnectFromRemoteHost
{
[socket disconnect];
}

-(void)onSocketDidDisconnect:(AsyncSocket *)sock
{
NSLog(@"Did Disconnect");
}

- (void)onSocket:(AsyncSocket *)sock willDisconnectWithError:(NSError *)err
{
NSLog(@"Disconnect Error: %@", [err localizedDescription]);
}

- (void)onSocket:(AsyncSocket *)sock didWriteDataWithTag:(long)tag
{
[socket readDataWithTimeout:-1 tag:0];
}

- (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
{
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSArray *dictArray = [[unarchiver decodeObjectForKey:@"DictArray"] retain];
    [unarchiver finishDecoding];
    [unarchiver release];
    for (NSDictionary *dict in dictArray) {
        if ([[dict objectForKey:@"Kind"] isEqualTo:@"New"])
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NewJob" object:self userInfo:dict];
        else if ([[dict objectForKey:@"Kind"] isEqualTo:@"Update"])
            [[NSNotificationCenter defaultCenter] postNotificationName:@"JobUpdate" object:self userInfo:dict];
    }
[socket readDataWithTimeout:-1 tag:0];
}

Help me stackoverflow, you’re my only hope!

  • 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-24T21:10:01+00:00Added an answer on May 24, 2026 at 9:10 pm

    I see 2 potential problems with your posted code. The first seems unlikely to be causing your problems, but I’ll post it anyway. In your client code you have:

    -(BOOL)onSocketWillConnect:(AsyncSocket *)sock 
    {
        [sock retain];
        [socket readDataWithTimeout:-1 tag:0];
        return YES;
    }
    

    I’m not sure why you would be retaining “sock” here. You already have a retained copy of the socket you created and this seems likely to result in a leak.

    As for the second problem, which is more likely to be the cause of your failures, here is what I think is happening. Looking at the documentation for AsyncSocket I see this:

    However, AsyncSocket is not thread-safe. You must only invoke methods on AsyncSocket from
    the thread/runloop on which the socket is configured. If you find yourself on a thread which
    is different from the thread on which AsyncSocket is running, and you need to invoke a
    method on AsyncSocket, then you must use a method like performSelector:onThread: to ensure
    the method is invoked on AsyncSocket’s thread (and thereby maintaining thread-safety).

    Your code that receives notifications and triggers a “later” write is likely in another thread, so even through the thread is valid the write fails to do what you expect. The AsyncSocket documentation goes on to suggest you use GCDAsyncSocket if you want thread safety.

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

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have just tried to save a simple *.rtf file with some websites and
I am trying to understand how to use SyndicationItem to display feed which is
I have a jquery bug and I've been looking for hours now, I can't
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I've got a string that has curly quotes in it. I'd like to replace
Seemingly simple, but I cannot find anything relevant on the web. What is the
I want use html5's new tag to play a wav file (currently only supported
I'm making a simple page using Google Maps API 3. My first. One marker

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.