views:

203

answers:

0

Hi all,

I am currently trying to connect an iPhone to a predetermined custom server. I have managed to make this connection using a simple easy to follow example I found in some forum. This code is as follows:

- (void)sendcmd:(NSString*)cmd {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *hostname= [defaults stringForKey:@"hostname"];

    NSHost *host=[NSHost hostWithName:hostname];

    if (host) {

      struct sockaddr_in addr;
      int sockfd;

      // Create a socket
      sockfd = socket( AF_INET, SOCK_STREAM, 0 );

      addr.sin_family = AF_INET;
      addr.sin_addr.s_addr = inet_addr([[host address] UTF8String]);
      addr.sin_port = htons( 2001 );

      int conn = connect(sockfd, &addr, sizeof(addr)); 

      if (!conn) {

          NSData* data = [cmd dataUsingEncoding:NSISOLatin1StringEncoding];

          ssize_t datasend = send(sockfd, [data bytes], [data length], 0);
          datasend++;

          //ssize_t    send(int, const void *, size_t, int) __DARWIN_ALIAS_C(send);

          close(sockfd);

      } else {
          // create a popup here!

          UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Connection failed to host " stringByAppendingString:hostname] message:@"Please check the hostname in the preferences." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
          [alert show];
          [alert release];
      }

    } else {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[@"Could not look up host " stringByAppendingString:hostname] message:@"Please check the hostname in the preferences." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
    }

}

Now I am looking to use this code but instead of sending a message, it will receive a message from the server. Will this require alot of alterations to this code? If anyone could provide me with an example of how to change it to do this or even some useful info about it I would be very grateful. I have had a look at Beej's Guide to network programming but I am new to programming and struggle to get my head round it.

Thank you for looking,

Chris