Search code examples
iphonetcpipodasyncsocket

iPhone/iPod receive messages from C# tcpip server using CocoaAsyncSocket


i'm trying to send/receive data over wifi to an iphone/ipodtouch app from a C# tcpip server. for this i used cocoaAsyncSocket from the google project. If i push a button and i send a request from ipod to server it returns the requested data(song title for example)..i want to know every second what song is playng...so from C# server i send at intervals of 1 second messages to my app. In my app in an timer with the interval of 1 second i call the asyncSocket read readDataWithTimeout method. My problem is that after 8-9 seconds that method is not called anymore. The connection to the server is still active and the C# server still sends data..

what i want to do is the following thing: -> winamp plays a song -> C# server asks winamp what songs is he playing and sends the song title to my app. -> iphone app receives the data and displays it

i don't know why the readDataWithTimeout method is not called anymore after a short period of time..Maybe because the short time between messages sent by the C# server?

Thank you, Sorin


Solution

  • i made it work..after a little more reading... so to read data when it arrives with AsyncSocket on unknown intervals i used the fallowing code(i don't know if is the best solution but it works for what i wanted):

    - (void) readDataFromSocket
    {
            [socket readDataWithTimeout:-1 tag:0];
    }
    
    - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag
    {
        NSData *strData = [data subdataWithRange:NSMakeRange(0, [data length])];
        NSString *msg = [[[NSString alloc] initWithData:strData encoding:NSUTF8StringEncoding] autorelease];
        if(msg)
        {
            if([msg isEqualToString:@"something"])
            {
                Do stuff
            }
            else
            {
                Do something else
                }
            }
        }
        else
        {
            NSLog(@"Error converting received data into UTF-8 String");
        }
        [socket readDataWithTimeout:-1 tag:0];
    }
    

    i call once in my application the readDataFromSocket method that calls the sockets [socket readDataWithTimeout:-1 tag:0] method. It should be called only once in the app because in the method - (void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag method in the last line i call again the [socket readDataWithTimeout:-1 tag:0]; which tells the socket to listen on the socket. When data arrives the socket will read it.

    hope it helps someone..