Search code examples
iphoneobjective-cnetwork-protocolscocoaasyncsocket

How to program a communication protocol with "iphone sockets"?


I've programmed a client-server application for Android and I'm doing the same for Iphone. The thing is that for the communication process, with the java server and the Android client, I've programmed something like this (in pseudo...):

data = read();
if ( data.compareTo("Something1") == 0) then
     write("Something2");
     data = read();
     if ( data.compareTo("Something3") == 0) then
          //End communitacion
     endif
endif

Now my problem is that with the "iphone sockets" I don't know how to do that. I'm using the AsyncScoket library, and with that library the read is not blocking (something that is complicated for me) and it uses callbacks that I don't really know how to use it correctly.

I guess that when a read is done, I should test in the proper callback if the data sent is equal to "Something1" or "Something2"... But, the first little problem is that it doesn't have any order.

I should say that I have no time to modify the protocol.

If someone could guide me, I would be so grateful. Or any code example where a network communication is done with the AsyncSocket library.

Thank you!


Solution

  • I've recently begun using asyncsocket along with a TCP java server. Perhaps this code may help?

    To write to the socket you need to call the following method from the asyncsocket object

    -(void)writeData:withTimeout:tag:;
    

    Data here should be an NSData object. You can easily convert strings to NSData by doing

    [someStringObject dataUsingEncoding:NSUTF8Encoding];
    

    To read from the socket just call this method

    -(void)readDataWithTimeOut:tag:;
    

    pass -1 for the timeout if you do not need a timeout.

    And that's it. Reading/Writing using cocoaasyncsocket is much easier than dealing with sockets in Java where you need datainputstream and dataoutputstream and other such stuff.

    Important delegate methods are

    -(void)onSocket:didReadData:withTag: gets called whenever the socket reads some data.
    

    Example of this delegate is..

    -(void)onSocket:(AsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag{
    
          NSString *string = [[NSString alloc] initWithBytes:[data bytes] 
                                                      length:[data length]
                                                    encoding:NSUTF8StringEncoding];
         //Do what ever comparison you'd like here.
    
    }
    

    If there is anything that you don't understand then let me know and I'll try and answer your doubts.