Apple Intelligence is now available on iPhone, iPad, and Mac!

Looks like no one’s replied in a while. To start the conversation again, simply ask a new question.

Problem with sockets on iPhone

Hi Everybody,

i am trying to develop a network application between an iPhone client and a Java server. I have a problem : I can't communicate the Server more than 3 times! I can send, receive and send or receive, send, and than receice. My iPhone crashes wenn I try to send and receive and than send and receive.

I used BSD-Sockets and many other frameworks (Asyncsockets, EDCommon, OmniNetworking...) and I had the same problem.

I thought that i had make a mistake in my server. I used the the multiclient java server example von Sun ( http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html) and I still had the same problem.

This is my code with BSD-Sockets:

- (IBAction)loginLogoutButtonPressed:(id)sender {
[spinner startAnimating];
if (isLoggedIn) {
[loginLogoutButton setTitle:@"Login"];
}
else {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *iHostname = [defaults stringForKey:@"server"];
NSString *iPort = [defaults stringForKey:@"port"];

struct sockaddr_in addr;
int sockfd;
sockfd = socket(AF INET,SOCKSTREAM,0);
addr.sin_family= AF_INET;
struct hostent *he = gethostbyname([iHostname UTF8String]);

struct in_addr **list = he->h addrlist;
addr.sin_addr = *list[0];
addr.sin_port = htons([iPort intValue]);
int conn = connect(sockfd,(struct sockaddr*) &addr, sizeof(addr));
if (!conn) {
NSString *req = @"ConReq";
NSData* data = [req dataUsingEncoding:NSISOLatin1StringEncoding];
send(sockfd, [data bytes], [data length], 0);

char response[100];
bzero(&response, sizeof(response));
read(sockfd, response, sizeof(response));
message.text = [NSString stringWithCString:response encoding:NSISOLatin1StringEncoding];

NSString *req1 = @"ConReq";
NSData* data1 = [req1 dataUsingEncoding:NSISOLatin1StringEncoding];
send(sockfd, [data1 bytes], [data1 length], 0);

bzero(&response, sizeof(response));
read(sockfd, response, sizeof(response));
message.text = [NSString stringWithCString:response encoding:NSISOLatin1StringEncoding];
close(sockfd);
message.text = [NSString stringWithCString:response encoding:NSISOLatin1StringEncoding];
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host " stringByAppendingString:iHostname] message:@"Please check the hostname in the preferences." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
[alert release];
}
[loginLogoutButton setTitle:@"Logout"];
}
isLoggedIn = !isLoggedIn;
[spinner stopAnimating];
}

Are IPhone and java uncompatible? Did I make a mistake in my code?

Regards,

arbifedi

MacBook Pro, Mac OS X (10.5.6)

Posted on Apr 8, 2009 6:12 AM

Reply
3 replies

Apr 8, 2009 2:24 PM in response to arbifedi

The connection with the server did work with NSStream on the simulator. Unfortunately, The iPhone don't have the header file NSHost.h and some other NSStream header 😟 I will tomorrow try to use CFSStream Socket exententions, since iPhone supports them...

If you find the problem with my BSD-Sockets code, let me now 🙂

Apr 9, 2009 2:50 AM in response to arbifedi

I solved the problem using CFStream Socket addition. It is like NSStream, but not so nice 😉

There is my code for anybody who want to use an iphone client to read an write on a server.


static void ReadStreamClientCallBack( CFReadStreamRef stream, CFStreamEventType type, void *clientCallBackInfo ) {
switch (type)
{
case kCFStreamEventEndEncountered:
{
CFReadStreamClose(stream);
break;
}
case kCFStreamEventErrorOccurred:
break;
case kCFStreamEventHasBytesAvailable:
{
UInt8 buffer[1024];
CFReadStreamRead(stream, buffer, 1024);
break;
}
case kCFStreamEventNone:
break;
case kCFStreamEventOpenCompleted:
break;
}
}
static void WriteStreamClientCallBack( CFWriteStreamRef stream, CFStreamEventType type, void *clientCallBackInfo ) {
switch (type)
{
case kCFStreamEventEndEncountered:
{
CFWriteStreamClose(stream);
break;
}
case kCFStreamEventErrorOccurred:
break;
case kCFStreamEventCanAcceptBytes:
{
NSString *reqStr = [NSString stringWithFormat: @"ConReq"];
const UInt8 *rawstring = (const UInt8 *)[reqStr UTF8String];
CFWriteStreamWrite(stream, rawstring, strlen((char *)rawstring));
}
case kCFStreamEventNone:
break;
case kCFStreamEventOpenCompleted:
break;
}
}
- (IBAction)loginLogoutButtonPressed:(id)sender {
[spinner startAnimating];
if (isLoggedIn) {
[loginLogoutButton setTitle:@"Login"];
}
else {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *iHostname = [defaults stringForKey:@"server"];
NSString *iPort = [defaults stringForKey:@"port"];

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
static const CFOptionFlags kReadNetworkEvents = kCFStreamEventEndEncountered |
kCFStreamEventErrorOccurred |
kCFStreamEventHasBytesAvailable |
kCFStreamEventOpenCompleted |
kCFStreamEventNone;
static const CFOptionFlags kWriteNetworkEvents = kCFStreamEventEndEncountered |
kCFStreamEventErrorOccurred |
kCFStreamEventCanAcceptBytes |
kCFStreamEventOpenCompleted |
kCFStreamEventNone;
CFStreamClientContext ctxt = {0,(void*)NULL,NULL,NULL,NULL};
CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault,(CFStringRef)iHostname);

CFStreamCreatePairWithSocketToCFHost(kCFAllocatorDefault, hostRef, [iPort intValue],
&readStream, &writeStream);
//CFSocketStreamPairSetSecurityProtocol(readStream, writeStream, kCFStreamSocketSecurityNone);

CFReadStreamSetClient(readStream, kReadNetworkEvents, ReadStreamClientCallBack, &ctxt);
CFWriteStreamSetClient(writeStream, kWriteNetworkEvents, WriteStreamClientCallBack, &ctxt);
CFReadStreamScheduleWithRunLoop(readStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFWriteStreamScheduleWithRunLoop(writeStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
CFReadStreamOpen(readStream);
CFWriteStreamOpen(writeStream);

[loginLogoutButton setTitle:@"Logout"];
}
isLoggedIn = !isLoggedIn;
[spinner stopAnimating];
}


Enjoy!

Apr 22, 2009 6:29 PM in response to arbifedi

Hi,

I have been trying to get your example to work, but every test I run I seem to get a bad pointer reference on the CFReadStreamOpen(readStream).

I have gone through everything I could think of to see if I could resolve it, but to no avail. Is there any chance you have a working demo I could look at?

I would really appreciate any help you could provide.

If you would like to send it to my e-mail you can send it to jlawton <at> zarksoft <dot> com.

Thanks for your time.

Regards,

Veri

Problem with sockets on iPhone

Welcome to Apple Support Community
A forum where Apple customers help each other with their products. Get started with your Apple Account.