Chilly Zhong
Chilly Zhong

Reputation: 16783

Question about Socket Streams on iPhone

I want to send a UIImage to a server with socket. I'm using this code from ADC:


- (IBAction)searchForSite:(id)sender

{

    NSString *urlStr = [sender stringValue];

    if (![urlStr isEqualToString:@""]) {

        [searchField setEnabled:NO];

        NSURL *website = [NSURL URLWithString:urlStr];

        if (!website) {

            NSLog(@"%@ is not a valid URL");

            return;

        }

        NSHost *host = [NSHost hostWithName:[website host]];

        // oStream is instance variable

        [NSStream getStreamsToHost:host port:80 inputStream:nil
            outputStream:&oStream];

        [oStream retain];

        [oStream setDelegate:self];

        [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop]

            forMode:NSDefaultRunLoopMode];

        [oStream open];

    }

}

First question: I want to create an NSOutputStream object, but I find that it can only be initilized with a file, a buffer, or memory. How can I output the stream to a socket then?

Second question: The ADC's reference tells us that the method getStreamsToHost:port:inputStream:outputStream: returns the object representing an output stream to the remote host. How can the host return the output stream to itself? And where can I add output stream in the code to send to the host

Upvotes: 0

Views: 2146

Answers (1)

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181270

First question:

You are already initializing it with a socket. NSStream's getStreamsToHost message already gives you a socket to talk to specified host, post. Whenever you want to write to the socket, just use oStream.

Second question:

Kind of answered in the first question. Keep in mind that you are opening a socket to port 80. So, probably you are running a WebServer on the remote host. And to be able to send an image to the remote server, you would need to implement HTTP protocol. Check my suggestion below. I think it will make your life easier.


A little suggestion:

I know you didn't ask this, but let me give you a suggestion. You are trying to send an image through a socket. I would use a higher level protocol such as HTTP or FTP to do that. Using a plain socket will force you to implement a new protocol yourself, not to mention the server side code to process incoming images.

So, if you use HTTP, just write a little server side script in your favorite WEB developing platform (.NET, PHP, Java, Python, RoR, CGI, whatever) and just use guidelines on this WebPage to submit the image on iPhone. It's way easier.

Upvotes: 2

Related Questions