开发者

Using socket API on IPhone

for a little project I have to do the following task on my IPhone:

  • open a TCP socket
  • send a command to the server
  • shutdown the WRITE part of the connection
  • read the response from the server
  • close the connection

I'm not experienced with 开发者_如何转开发socket programming - I've just started with network programming and I've already used the CFStream interface. But obviously streams are not adequate for this task.

Who can point me in the right direction? I tried to find a tutorial on Apples website about sockets, but there is nothing.


Take a look at CoreFoundation's CFSocket. You can integrate it easily into your app's run loop, so there's no messing around with threads. This free book excerpt shows you how to use it.

CFSocket is a wrapper around a bsd socket, and lets you access the raw socket handle if ever you need to set special socket options (such as multicast).

If you're open to using 3rd-party libraries, CocoaAsyncSocket seems like a nice solution (never tried it myself).


I'm not an iPhone developer, but I was curious about your question so I had a look around.

I found this page: Sockets on iPhone

Here's the code:

- (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];
    }

}

A poster goes on to also suggest this library: entropydb - SocketWrapper

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜