Search code examples
iossocketsasyncsocket

iOS: read and write in a socket (tcp connection)


In my app I should comunicate with a server side (a little device that do as a server).

My principal operation is to write a sequence of 17 byte and read the result. I used GCDAsyncSocket but it don't give me ever a good result.

I want ask to you if is there a way to do this job in an efficient way.


Solution

  • Don't do it on main thread. As your user case is simple, I write a simple example. I don't test it by the way...

    int sock = socket(AF_INET, SOCK_STREAM, 0) ;
    struct sockaddr_in server_addr ;
    bzero(&server_addr, sizeof(server_addr)) ;
    server_addr.sin_port = htons(1025) ;
    server_addr.sin_addr.s_addr = inet_addr("192.168.1.5") ;
    server_addr.sin_family = AF_INET ;
    
    int i = connect(sock, (const struct sockaddr *)&server_addr, sizeof(server_addr)) ;
    if (i >= 0) {
        char writeBuf[17] = "12345678901234567" ;
        long w = write(sock, writeBuf, 17) ;
        if (w > 0) {
            char bufferRead[1024] ;
            long r = read(sock, bufferRead, sizeof(bufferRead)) ;
            if (r > 0) {
                // success
            }
        }
    }
    close(sock) ;