How to create an iPhone based Web Service

The iPhone provides no disk access. The backup mechanism hides your files into mdbackup archives. Apple disabled attachments for email. So what do you do when you want to share your data with the world. Creating your own web server is one way to provide a connection between your iPhone data and your users.
Building a barebones web server is a lot easier than you might think. To create a server, just listen to a port for incoming requests. You can use a set port number or listen to a random port, as in the code that follows.

This code shows some very basic socket set-up -- and yes, it's very old-style, there are nice CFNetwork solutions that are much cleaner with callbacks -- and a listener loop.
With a port and a listener loop, you can just grab requests from a browser client, process them and send back HTML-compliant data, as you 'll see in part 2. All the web request processing is handled in a separate method, handleWebRequest which pulls the actual data from the socket, interprets it and then responds to it.

Sockets are a great way to work with the iPhone for all sorts of applications -- serving web data like this is just one application. You can also do remote application control, general computer-to-computer communication, and more. Once you set up the socket, you can use your imagination to define what information to pass.

- (void) startServer
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
int socketfd;
socklen_t length;
static struct sockaddr_in cli_addr;
static struct sockaddr_in serv_addr;
// Set up socket
if((listenfd = socket(AF_INET, SOCK_STREAM,0)) <0)
{
isServing = NO;
return;
}
// Serve to a random port
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = 0;

// Bind
if(bind(listenfd, (struct sockaddr *)&serv_addr,
sizeof(serv_addr)) <0)
{
isServing = NO;
return;
}
// Find out what port number was chosen.
int namelen = sizeof(serv_addr);
if (getsockname(listenfd, (struct sockaddr *)&serv_addr,
(void *) &namelen) < 0)
{
close(listenfd);
isServing = NO;
return;
}

chosenPort = ntohs(serv_addr.sin_port);
// Listen
if(listen(listenfd, 64) < 0)
{
isServing = NO;
return;
}
// Respond to requests until the service shuts down
while (1 > 0) {
length = sizeof(cli_addr);
if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr,
&length)) < 0)
{
isServing = NO;
return;
}
[self handleWebRequest:socketfd];
}
[pool release];
}

No comments:

 
Top Blogs