TCP Socket Programming in iOS. Server Client Response

僤鯓⒐⒋嵵緔 提交于 2019-12-11 17:57:17

问题


I'm almost done with this task but i'm stuck a point due to which i'm getting partial result. I have server(linux or windows) and client(iOS) between which TCP IP socket connection exist. I have used form load in my iphone simulator where the connection between server and iphone happens automatically as the application opens. Server send the data back what ever I send on simulator and print it in log. But i'm not able to exactly receive the whole response. For "Innovations" I receive maybe just "in" or "Innova"etc.. Below are the code snippets.

void TCPClient()
{

    CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, host, port, &readStream, &writeStream);
    [NSThread sleepForTimeInterval:2]; //Delay


    CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    if(!CFWriteStreamOpen(writeStream))
    {
        NSLog(@"Error Opening Socket");
    }
    else
    {
        UInt8 buf[] = "Innovations";
        int bytesWritten = CFWriteStreamWrite(writeStream, buf, strlen((char*)buf));
        NSLog(@"Written: %d", bytesWritten);
    }
    CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
    if(!CFReadStreamOpen(readStream))
    {
        NSLog(@"Error reading");
    }
    else
    {
        UInt8 bufr[15];
        int bytesRead  = CFReadStreamRead(readStream, bufr,strlen((char*)bufr));
        NSLog(@"Read: %d", bytesRead);
        NSLog(@"buffer: %s", bufr);
    }
}

Notice in the read I did change the array size. But I still get the error. Same in the case of IBAction of a button. Even in that for every click i'm sending a data and i'm not getting the response of the same data.

Can valuable suggestion???


回答1:


One error is that

int bytesRead  = CFReadStreamRead(readStream, bufr,strlen((char*)bufr));

should be

int bytesRead  = CFReadStreamRead(readStream, bufr, sizeof(bufr));

The last parameter of CFReadStreamRead is the capacity of the read buffer and determines the maximum number of bytes read. strlen((char*)bufr) is the length of the string currently in the buffer. You should also NULL-terminat the string in bufr before printing it.

With this modification, your program might work with short strings. But there will be problems as soon as you try to send/receive larger amounts of data.

A socket write can write less bytes than you asked it to, and a socket read can return less bytes than you requested.

Have a look at the Stream Programming Guide which describes how to register the socket streams with the runloop and handle stream events asynchronously.



来源:https://stackoverflow.com/questions/15583366/tcp-socket-programming-in-ios-server-client-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!