开发者

Simple Iphone Client Connection to Server

Thanks in advance those who view my question. i am new to programming and also new to Objective-c programming, i am creating a simple client that will connect to a daytime server and request what time and date it is then print it to the screen, i have watched and read lots of tutorials right now and came up with the below code but i have a problem i cant read input from user that will enter the server address and i will use that server address in order to connect to server here is my code

my socket codes in my controller.m file

@interface NSStream (MyAdditions)

+ (void)getStreamsToHostNamed:(NSString *)hostName 
                         port:(NSInteger)port 
                  inputStream:(NSInputStream **)inputStreamPtr 
                 outputStream:(NSOutputStream **)outputStreamPtr;

@end

@implementation NSStream (MyAdditions)              
+ (void)getStreamsToHostNamed:(NSString *)hostName 
                         port:(NSInteger)port 
                  inputStream:(NSInputStream **)inputStreamPtr 
                 outputStream:(NSOutputStream **)outputStreamPtr
{
    CFReadStreamRef     readStream;
    CFWriteStreamRef    writeStream;

    assert(hostName != nil);
    assert( (port > 0) && (port < 65536) );
    assert( (inputStreamPtr != NULL) || (outputStreamPtr != NULL) );

    readStream = NULL;
    writeStream = NULL;

    CFStreamCreatePairWithSocketToHost(
                                       NULL, 
                                       (CFStringRef) hostName, 
                                       port, 
                                       ((inputStreamPtr  != nil) ? &readStream : NULL),
                                       ((outputStreamPtr != nil) ? &writeStream : NULL)
                                       );

    if (inputStreamPtr != NULL) {
        *inputStreamPtr  = [NSMakeCollectable(readStream) autorelease];
    }
    if (outputStreamPtr != NULL) {
        *outputStreamPtr = [NSMakeCollectable(writeStream) autorelease];
    }
}

@end

My Connection address and port

@implementation iPhoneClientViewController

-(void) connect {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *address = [defaults stringForKey:@"Address"]; // this is default one 
    if(!address) address = @"localhost";
    NSLog(@"ADDRESS %@",address);

    [NSStream getStreamsToHostNamed: address port:13 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];
}

my defaults are

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD开发者_如何学Python PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
  <dict>
   <key>Title</key>
   <string>iPhoneClient</string>
   <key>StringsTable</key>
   <string>Root</string>
   <key>PreferenceSpecifiers</key>
   <array>
    <dict>
      <key>Type</key>
      <string>PSTextFieldSpecifier</string>
      <key>Title</key>
      <string>Server IP</string>
      <key>Key</key>
      <string>Address</string>
      <key>DefaultValue</key>
      <string>localhost</string>
      <key>IsSecure</key>
      <false/>
      <key>KeyboardType</key>
      <string>NumbersAndPunctuation</string>
      <key>AutoCorrectType</key>
      <string>No</string>
    </dict>
   </array>
  </dict>
</plist>

i put a text field to my ViewController.m

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"Text Field contents %@",textField.text);
    [textField resignFirstResponder];
    return YES;
}

and when button clicked i put

- (IBAction)connectCommand:(id)sender {
    // NSString *address = textField.text; // this is gives me error textField  undeclared
    // then i try this one
    NSString *address = text.text;
    if( iStream != nil) return;
    [self connect];
}

then i run program i enter the address then i click to connect button but it doesnt work it gives me following errors on output screen

2011-10-03 17:49:14.903 iPhoneClient[360:b303] Text Field contents 64.90.182.55 
2011-10-03 17:49:16.096 iPhoneClient[360:b303] ADDRESS localhost
2011-10-03 17:49:16.101 iPhoneClient[360:b303] >> : NSStreamEventErrorOccurred
2011-10-03 17:49:16.102 iPhoneClient[360:b303] << : NSStreamEventErrorOccurred

my event handling is like following

- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent
{
    NSString *io;
    if (theStream == iStream) io = @">>";
    else io = @"<<";

    NSString *event;
    switch (streamEvent)
    {
        case NSStreamEventNone:
            event = @"NSStreamEventNone - Can not connect to the host!";
            break;
        case NSStreamEventOpenCompleted:
            event = @"NSStreamEventOpenCompleted";
            break;
        case NSStreamEventHasBytesAvailable:
            event = @"NSStreamEventHasBytesAvailable";
            if (theStream == iStream)
            {
                //read data
                uint8_t buffer[1024];
                int len;
                while ([iStream hasBytesAvailable])
                {
                    len = [iStream read:buffer maxLength:sizeof(buffer)];
                    if (len > 0)
                    {
                        NSString *input = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
                        if (nil != input)
                        {
                            //do something with data
                            NSLog(@"%@",input);
                        }
                    }
                }
            }
            break;
        case NSStreamEventHasSpaceAvailable:
            event = @"NSStreamEventHasSpaceAvailable";
            break;
        case NSStreamEventErrorOccurred:
            event = @"NSStreamEventErrorOccurred";
            break;
        case NSStreamEventEndEncountered:
            event = @"NSStreamEventEndEncountered";
            [self disconnect];
            break;
        default:
            event = @"** Unknown";
    }

    NSLog(@"%@ : %@", io, event);
}

can any one help me with my code? or suggests me a good me a good tutorial that i can see examples of codes and learn more stuff about sockets.

=====================================================================================================

alright since i am new it is not allowed to reply my own post so i will edit it

i think i will go with low level, yes dealing with xml is little bit complicating so i just disabled the parts

//NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    //NSString *address = [defaults stringForKey:@"Address"];
    //if(!address) address = @"localhost";]

and put this code

    NSString *address = [text text];
    NSLog(@"ADDRESS %@",address);

now in my output screen i get following =

2011-10-03 18:58:57.758 iPhoneClient[424:b303] Text Field contents 64.90.182.55 
2011-10-03 18:58:58.627 iPhoneClient[424:b303] ADDRESS 64.90.182.55 
2011-10-03 18:58:58.685 iPhoneClient[424:b303] >> : NSStreamEventOpenCompleted
2011-10-03 18:58:58.686 iPhoneClient[424:b303] << : NSStreamEventOpenCompleted
2011-10-03 18:58:58.686 iPhoneClient[424:b303] << : NSStreamEventHasSpaceAvailable
2011-10-03 18:58:58.696 iPhoneClient[424:b303] >> : NSStreamEventHasBytesAvailable
2011-10-03 18:58:58.698 iPhoneClient[424:b303] >> : NSStreamEventEndEncountered

i thinks it says it connected but since i do nothing with data it is terminating itself because i put a run loop above?

now anyone know how can i fetch and print date and time from server?


High Level Feedback:

I would suggest that communicating with your server using byte streams is too low a level.

Instead, consider using JSON or XML as a more manageable format. By combining this with a RESTful API you can use HTTP Requests from iOS, and communicate with your server in a more productive, portable, and manageable way.

Hope that helps.


in methods:

NSString *address = [text text];

when user tab return key on keyboard:

-(BOOL)textFieldShouldReturn: (UITextField *)textField {
    NSLog(@"Text Field contents %@",textField.text);
    [textField resignFirstResponder];
    return YES;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜