Search Results

Search found 12 results on 1 pages for 'nsstream'.

Page 1/1 | 1 

  • Cocoa NSStream TCP connection to FTP

    - by Chuck
    Hi, I'm new to Cocoa, but not to programming. Recently I decided I wanted to write a FTP client for Mac, and so I first made it in the language I'm most comfortable in (on Windows), and then moved on to Cocoa when I had the workings of FTP communications down. My question is (apparently) a bit controversial: How do I establish a read/writeable connection to (a ftp server)? What I have so far (non working obviously): NSInputStream *iStream; NSOutputStream *oStream; NSHost *host = [NSHost hostWithAddress:@"127.0.0.1"]; [NSStream getStreamsToHost:host port:3333 inputStream:&iStream outputStream:&oStream]; // ftp port: 3333 [iStream retain]; [oStream retain]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream setDelegate:self]; [oStream setDelegate:self]; // which is not implemented apparently [iStream open]; [oStream open]; // .... [iStream write: (const uint8_t *)buf maxLength:8]; Which is partially based on http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/Streams/Articles/NetworkStreams.html Now, why have I chosen NSStream? Because while this question is merely about how to connect to a FTP stream, my whole project will also include SSL and as far as I've been able to search here and on google, NSStream is capable of "switching" to a SSL connection. I've not been able to see the connection being made (which I'm usually able to do), but I also heard something about having to write to the stream before the stream will open? Any pointers are greatly appreciated, and sorry if my question is annoying - I'm new to Cocoa :)

    Read the article

  • NSStream sockets missing data

    - by Chris T.
    I am trying to pull some sample data from FreeDB as a proof of concept, but I am having a tough time retrieving all of the data off the incoming stream (I am only getting the last bits for the final query listed here (if handshakeCode = 3) I think this may be something with the threading on the main runloop, but I am not sure. Odd thing is when the buffer size is larger than 1-2 bytes (which works as expected), I seem to be losing access to the data programmatically (the totalOutput variable on the first set of data is incomplete). I set up a packet capture, and it looks like those 1024 bytes are coming across the wire, but the app just isn't working with it. It looks like the next event is coming through and basically taking over. I tried using an NSLock to no avail as well. If I drop the buffer size down to 1 or 2, things seem to be reading just fine. This is probably obvious to someone who does this all the time, but this is my first foray into this with something I am familiar with, technology wise in other languages / platforms. The following code will show you what is happening. Run with the buffer set to 1024, and you will see a short final string, but once you set it to 1, you will see the amount of data I was expecting (I was even expecting it to be split, so that's not a big worry) #import <Foundation/Foundation.h> #import <Cocoa/Cocoa.h> //STACK OVERFLOW CODE: @interface stackoverflow : NSObject <NSStreamDelegate> { NSInputStream *iStream; NSOutputStream *oStream; int handshakeCode; NSString *selectedDiscId; NSString *selectedGenre; } -(void)getMatchesFromFreeDB; -(void)sendToOutputStream:(NSString*)command; @end @implementation stackoverflow -(void)getMatchesFromFreeDB { NSHost *host = [NSHost hostWithName:@"freedb.freedb.org"]; [NSStream getStreamsToHost:host port:8880 inputStream:&iStream outputStream:&oStream]; [iStream retain]; [oStream retain]; [iStream setDelegate:self]; [oStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream open]; [oStream open]; handshakeCode = 0; //not done any processing } -(void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { switch(eventCode) { case NSStreamEventOpenCompleted: { NSLog(@"Stream open completed"); break; } case NSStreamEventHasBytesAvailable: { NSLog(@"Stream has bytes available"); if (aStream == iStream) { NSMutableString *totalOutput = [NSMutableString stringWithString:@""]; //read data uint8_t buffer[1024]; int len; while ([iStream hasBytesAvailable]) { len = [iStream read:buffer maxLength:sizeof(buffer)]; if (len 0) { NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding]; //this could have also been put into an NSData object if (nil != output) { //append to the total output [totalOutput appendString:output]; } } } NSLog(@"OUTPUT , %i:\n\n%@", [totalOutput lengthOfBytesUsingEncoding:NSUTF8StringEncoding], totalOutput); NSArray *outputComponents = [totalOutput componentsSeparatedByString:@" "]; //Attempt to get handshake code, since we haven't done it yet: if (handshakeCode == 1) { //we are just getting the sign-on banner: //let's move on: handshakeCode = 2; } else if (handshakeCode == 2) { handshakeCode = [[outputComponents objectAtIndex:0] intValue]; if (handshakeCode == 200) { NSLog(@"---Handshake OK %i", handshakeCode); NSMutableString *query = [NSMutableString stringWithString:@"cddb query f3114b11 17 225 19915 36489 54850 69425 87025 103948 123242 136075 152817 178335 192850 211677 235104 262090 284882 308658 4430\n"]; handshakeCode = 3; [self sendToOutputStream:query]; } } else if (handshakeCode == 3) { //now, we are reading out the matches: if ([[outputComponents objectAtIndex:0] intValue] == 200) //found exact match: { NSLog(@"Found exact match"); selectedGenre = [outputComponents objectAtIndex:1] ; selectedDiscId = [outputComponents objectAtIndex:2]; if (selectedGenre && selectedDiscId) { //send off the request to get the entry: NSString *query = [NSString stringWithFormat:@"cddb read %@ %@\n", selectedGenre, selectedDiscId]; [self sendToOutputStream:query]; handshakeCode = 4; } } } } break; } case NSStreamEventEndEncountered: { NSLog(@"Stream event end encountered"); break; } case NSStreamEventErrorOccurred: { NSLog(@"Stream error occurred"); break; } case NSStreamEventHasSpaceAvailable: { NSLog(@"Stream has space available"); if (aStream == oStream) { if (handshakeCode == 0) { handshakeCode = 1; [self sendToOutputStream:@"cddb hello stackoverflow localhost.localdomain test .01BETA\n"]; } } break; } } } -(void)sendToOutputStream:(NSString*)command { const uint8_t *rawCommand = (const uint8_t *)[command UTF8String]; [oStream write:rawCommand maxLength:strlen(rawCommand)]; NSLog(@"Sent command: %@",command); } @end int main (int argc, const char * argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; stackoverflow *test = [[stackoverflow alloc] init]; [test getMatchesFromFreeDB]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop run]; [pool drain]; return 0; } Any help is much appreciated! Thanks

    Read the article

  • Cocoa NSStream works with SSL, with socks5, but not at the same time

    - by Evan D
    Upon connecting (to an FTP, at first without SSL) I run: NSArray *objects = [NSArray arrayWithObjects:@"proxy.ip", [NSNumber numberWithInt:1080], NSStreamSOCKSProxyVersion5, @"user", @"pass", nil]; NSArray *keys = [NSArray arrayWithObjects:NSStreamSOCKSProxyHostKey, NSStreamSOCKSProxyPortKey, NSStreamSOCKSProxyVersionKey, NSStreamSOCKSProxyUserKey, NSStreamSOCKSProxyPasswordKey, nil]; NSDictionary *proxyDictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; [iStream retain]; [iStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [iStream setProperty:proxyDictionary forKey:NSStreamSOCKSProxyConfigurationKey]; [iStream open]; same for iStream. This allows me to connect succesfully through a socks5 proxy. If I continue without setProperty:proxyDictionary... (socks5 disabled) I would tell the server to switch to SSL, and then successfully apply these settings to the in/output streams, thus giving me a SSL connection: NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:1]; [settings setObject:(NSString *)NSStreamSocketSecurityLevelTLSv1 forKey:(NSString *)kCFStreamSSLLevel]; // to allow selfsigned certificates: [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot]; [iStream retain]; [iStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; CFReadStreamSetProperty((CFReadStreamRef)iStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings); [iStream setProperty:NSStreamSocketSecurityLevelTLSv1 forKey:NSStreamSocketSecurityLevelKey]; same for oStream. All of which works fine if I disable socks5. If I turn it on (line 7 in the first snippit) I lose contact when applying the SSL settings. If I had to guess, I'd think it's losing some properties when applying (ssl) "settings"? Please help :) Evan

    Read the article

  • handling NSStream events when using EASession in MonoTouch

    - by scotru
    Does anyone have an example of how to handle read and write NSStream events in Monotouch when working with accessories via EASession? It looks like there isn't a strongly typed delegate for this and I'm having trouble figuring out what selectors I need to handle on the delegates of my InputStream and OutputStream and what I actually need to do with each selector in order to properly fill and empty the buffers belonging to the EASession object. Basically, I'm trying to port Apple's EADemo app to Monotouch right now. Here's the Objective-C source that I think is relevant to this problem: / / asynchronous NSStream handleEvent method - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { switch (eventCode) { case NSStreamEventNone: break; case NSStreamEventOpenCompleted: break; case NSStreamEventHasBytesAvailable: [self _readData]; break; case NSStreamEventHasSpaceAvailable: [self _writeData]; break; case NSStreamEventErrorOccurred: break; case NSStreamEventEndEncountered: break; default: break; } } / low level write method - write data to the accessory while there is space available and data to write - (void)_writeData { while (([[_session outputStream] hasSpaceAvailable]) && ([_writeData length] > 0)) { NSInteger bytesWritten = [[_session outputStream] write:[_writeData bytes] maxLength:[_writeData length]]; if (bytesWritten == -1) { NSLog(@"write error"); break; } else if (bytesWritten > 0) { [_writeData replaceBytesInRange:NSMakeRange(0, bytesWritten) withBytes:NULL length:0]; } } } // low level read method - read data while there is data and space available in the input buffer - (void)_readData { #define EAD_INPUT_BUFFER_SIZE 128 uint8_t buf[EAD_INPUT_BUFFER_SIZE]; while ([[_session inputStream] hasBytesAvailable]) { NSInteger bytesRead = [[_session inputStream] read:buf maxLength:EAD_INPUT_BUFFER_SIZE]; if (_readData == nil) { _readData = [[NSMutableData alloc] init]; } [_readData appendBytes:(void *)buf length:bytesRead]; //NSLog(@"read %d bytes from input stream", bytesRead); } [[NSNotificationCenter defaultCenter] postNotificationName:EADSessionDataReceivedNotification object:self userInfo:nil]; } I'd also appreciate any architectural recommendations on how to best implement this in monotouch. For example, in the Objective C implementation these functions are not contained in any class--but in Monotouch would it make sense to make them members of my

    Read the article

  • NSStream on Background didn't call

    - by Iphone Developer
    - (void)applicationDidEnterBackground:(UIApplication *)application { NSOutputStream *outputStream; NSInputStream *inputStream; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ [inputStream setDelegate:self]; [outputStream setDelegate:self]; [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }); } Input,OutputStream delegate didn't call.What i am doing wrong.

    Read the article

  • iPhone, I can send accelerometer data via wifi only 248 lines

    - by newbie
    I have created one application on iPhone. I build an application that gather accelerometer value and pass this value to c# server in realtime via wifi connection. I use NSStream with IP and port number. I was working perfectly, but now I realize that it stops after fetch value only 248 lines. I tried to write this value in text file locally on iPhone. I can obtain more than 260 lines of data. Therefore, I suspect that it has some limitation or other problems on NSStream of wifi connection.

    Read the article

  • Problems in getting data from CFStreamCreatePairWithSocketToHost

    - by gkedmi
    Hi I'm building an iPhoe app with a socket to a PC app , I need to get an image from this PC app. It's my first time using "CFStreamCreatePairWithSocketToHost".After I establish the socket with "NSOperation" I call CFStreamClientContext streamContext = {0, self, NULL, NULL, NULL}; BOOL success = CFReadStreamSetClient(myReadStream, kMyNetworkEvents,MyStreamCallBack,&streamContext); CFReadStreamScheduleWithRunLoop(myReadStream, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode); then I call CFWriteStreamWrite(myWriteStream, &writeBuffer, 3); // Open read stream. if (!CFReadStreamOpen(myReadStream)) { // Notify error } . . . while(!cancelled && !finished) { SInt32 result = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.25, NO); if (result == kCFRunLoopRunStopped || result == kCFRunLoopRunFinished) { break; } if (([NSDate timeIntervalSinceReferenceDate] - _lastRead) MyConnectionTimeout) { // Call timed out cancelled = YES; break; } // Also handle stream status CFStreamStatus status = CFReadStreamGetStatus(myReadStream); } and then when I get "kCFStreamEventHasBytesAvailable" I use while (CFReadStreamHasBytesAvailable(myReadStream)) { CFReadStreamRead(myReadStream, readBuffer, 1000); //and buffer the the bytes } It's unpredictable , sometimes I get the whole picture , sometime I got just part of it , and I can't understand what make the different. can someone has an idea what is wrong here? thanks

    Read the article

  • Settings for RTMP and AS 3.0

    - by coderex
    Hi, Is there any extra code need for using rtmp with AS3. I have the code like this. Is that enough for rtmp or any other code needed? var strSource:String = "rtmp://myserver.com/file.flv"; var ncConnection = new NetConnection(); var nsStream = new NetStream(ncConnection); nsStream.play(strSource);

    Read the article

  • establishing a socket connection from iPhone to MAC/PC

    - by user319572
    Hello, I just started getting into XCode and Co. What I am trying is to send accelerometer data via WLAN to a PC or MAC over a Socket connection. I am trying at the moment with the iPhone simulator, on the other site a netbook with a JAVA program shall receive a test string for starters. Unfortunately my socket will not initialize. What am I doing wrong? NSString *recStr = @"192.168.0.5"; //String with receiver IP NSHost *hoster = [NSHost hostWithName:recStr]; //create a host NSOutputStream *sendData; //create an output stream [NSStream getStreamsToHost:hoster port:8000 inputStream:nil outputStream:&sendData]; [sendData retain]; [sendData setDelegate:self]; [sendData open]; A warning says NSStream may not respond to '+getStreamsToHost:inputSream:outputStream:' So I guess parameters are wrong. But why and how to do it right? The program starts but I don't think I can send anything as long as this warning shows up (have not tried though). Thank you in advance, Andreas

    Read the article

  • send keystrokes from iphone to PC

    - by Matt Facer
    hi guys. I'm looking to create a simple app which will send keystrokes from an iphone to a PC. I understand that I will need to have a program on my PC "listening"... I've been looking in to AsyncSocket and NSStream, but there are no tutorials which really make it clear to understand. Does anyone know if this is right? I basically want to interact with a program on my PC which listens for keystrokes to control it. Does anyone know of a tutorial or place where I could start to learn this? (I've written iphone apps before, but I am new to networking)

    Read the article

  • Cocoa Read NSInputStream from FTP connection

    - by Chuck
    Hi, I (apparently) manage to make a ftp connection, but fail to read anything from it, and with good cause: I don't reach the reading until the connection has timed out. Here's my code: NSHost *host = [NSHost hostWithAddress:@"127.0.0.1"]; [NSStream getStreamsToHost:host port:3333 inputStream:&iStream outputStream:&oStream]; NSMutableDictionary *settings = [NSMutableDictionary dictionaryWithCapacity:1]; [settings setObject:(NSString *)NSStreamSocketSecurityLevelTLSv1 forKey:(NSString *)kCFStreamSSLLevel]; [settings setObject:[NSNumber numberWithBool:YES] forKey:(NSString *)kCFStreamSSLAllowsAnyRoot]; [iStream retain]; [iStream setDelegate:self]; [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; CFReadStreamSetProperty((CFReadStreamRef)iStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);forKey:NSStreamSocketSecurityLevelKey]; [iStream open]; [oStream retain]; [oStream setDelegate:self]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; CFWriteStreamSetProperty((CFWriteStreamRef)oStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings); forKey:NSStreamSocketSecurityLevelKey]; [oStream open]; NSMutableData *returnMessage = [NSMutableData dataWithLength: 300]; [iStream read: [returnMessage mutableBytes] maxLength: 300]; NSString *readData = [[NSString alloc] initWithBytes: [returnMessage bytes] length: 300 encoding: NSUTF8StringEncoding]; NSRunAlertPanel(@"response", readData, nil, nil, nil); I have not sent a request to the FTP to switch to ssl yet. Any help is greatly appreciated as I find Xcode quite horrible for debugging (no exception or error msg on failed steps what so ever). Chuck

    Read the article

  • Reading Certificates on iOS Problem

    - by David Schiefer
    I am trying to read certificates from various URLs in iOS. My code however is not working well - the array that should return the information I need always returns null. What am I missing? - (void)findCertificate:(NSString *)url { NSInputStream*input = [[NSInputStream inputStreamWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://store.writeitstudios.com"]]] retain]; [input setDelegate:self]; [input scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; [input open]; NSLog(@"Status: %i",[input streamStatus]); } - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode { NSLog(@"handle Event: %i",eventCode); if (eventCode == NSStreamStatusOpen) { NSArray *certificates = (NSArray*)CFReadStreamCopyProperty((CFReadStreamRef)aStream, kCFStreamPropertySSLPeerCertificates); NSLog(@"Certs: %@",CFReadStreamCopyProperty((CFReadStreamRef)aStream, kCFStreamPropertySSLPeerCertificates)); if ([certificates count] > 0) { SecCertificateRef certificate = (SecCertificateRef)[certificates objectAtIndex:0]; NSString *description = (NSString*)SecCertificateCopySubjectSummary(certificate); NSData *data = (NSData *)SecCertificateCopyData(certificate); NSLog(@"Description: %@",description); } } } And yes, I am aware that I am leaking memory. This is just a snippet.

    Read the article

1