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???
One error is that
should be
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 inbufr
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.