Problem with sockets on iPhone
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)