1

提前感谢那些查看我的问题的人。我是编程新手,也是 Objective-c 编程新手,我正在创建一个简单的客户端,它将连接到白天服务器并请求它是什么时间和日期,然后将其打印到屏幕上,我已经观看并阅读了很多教程现在并想出了下面的代码,但我有一个问题,我无法读取将输入服务器地址的用户输入,我将使用该服务器地址连接到服务器这是我的代码

我的 controller.m 文件中的套接字代码

@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

我的连接地址和端口

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

我的默认值是

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD 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>

我在 ViewController.m 中添加了一个文本字段

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

当我点击按钮时

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

然后我运行程序我输入地址然后我点击连接按钮但它不起作用它在输出屏幕上给我以下错误

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

我的事件处理如下

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

任何人都可以帮我处理我的代码吗?或向我推荐一个很好的教程,我可以查看代码示例并了解有关套接字的更多内容。

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

好吧,因为我是新人,所以不允许回复我自己的帖子,所以我会编辑它

我想我会使用低级别,是的,处理 xml 有点复杂,所以我只是禁用了这些部分

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

并把这段代码

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

现在在我的输出屏幕中我得到以下=

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

我认为它说它已连接,但由于我对数据什么都不做,它会自行终止,因为我在上面放了一个运行循环?

现在有人知道我如何从服务器获取和打印日期和时间吗?

4

2 回答 2

1

高层反馈:

我建议使用字节流与您的服务器进行通信的级别太低了。

相反,请考虑使用 JSON 或 XML 作为更易于管理的格式。通过将其与 RESTful API 相结合,您可以使用来自 iOS 的 HTTP 请求,并以更高效、可移植和可管理的方式与您的服务器通信。

希望有帮助。

于 2011-10-03T22:07:21.880 回答
1

在方法中:

NSString *address = [text text];

当键盘上的用户制表符返回键时:

-(BOOL)textFieldShouldReturn: (UITextField *)textField {
    NSLog(@"Text Field contents %@",textField.text);
    [textField resignFirstResponder];
    return YES;
}
于 2011-11-09T22:50:35.907 回答