简体   繁体   English

使用NSOutputStream将当前时间输出到服务器

[英]Using NSOutputStream to output the current time to the Server

I'm Using NSOutputStream to Output data from the client (IOS device ) to the server (PC Device). 我正在使用NSOutputStream将数据从客户端(IOS设备)输出到服务器(PC设备)。 I can send data successfully to the server, I just want to add the Current Time using NSOutputStream. 我可以将数据成功发送到服务器,我只想使用NSOutputStream添加当前时间。

How can i send the current time using NSOutputStream? 如何使用NSOutputStream发送当前时间?

Here's my code 这是我的代码

- (IBAction)button1:(id)sender {

    NSString *response  = @" Today's Sunny  \n  ";
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    [outputStream write:[data bytes] maxLength:[data length]];

    NSDate *currentTime = [NSDate date]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"hh:mm:ss"];
    _timer.text = [formatter stringFromDate:currentTime];
    //_timer is A label just for testing
    ///I'm trying to use outputStream to output currentTime like this
   /// [outputStream write:[currentTime bytes] maxLength:[CurrentTime length]];
}

You need to convert the formatted time string to data, the way you are already doing with the response, as long as the other side of the stream is just expecting text. 您需要将格式化的时间字符串转换为数据,就像处理响应一样,只要流的另一侧只是期待文本即可。 It can often be easier to use the -UTF8String method directly instead of using NSData: 直接使用-UTF8String方法而不是使用NSData通常会更容易:

[outputStream write:[string UTF8String]
          maxLength:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];

In the end, you are sending over raw bytes on an NSStream. 最后,您将通过NSStream发送原始字节。 NSData is obvious how to do that, but you need to get the exact c-string length if you are using character bytes -- so you can use the UTF8String and strlen() of that, or the lengthOfBytesUsingEncoding method as above. NSData很明显是这样做的方法,但是如果您使用字符字节,则需要获取确切的c字符串长度-因此,您可以使用UTF8String和strlen()或上述的lengthOfBytesUsingEncoding方法。

Here's the Complete answer 这是完整的答案

    NSDate *currentTime = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"hh:mm:ss"];
    NSString *timeString = [formatter stringFromDate:currentTime];
    [outputStream write:[timeString UTF8String]
              maxLength:[timeString lengthOfBytesUsingEncoding:NSUTF8StringEncoding]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM