NSStream与发送数据的服务器问题的连接

时间:2015-10-05 19:25:17

标签: ios objective-c sockets network-programming nsstream

我正在尝试使用NSStream与java服务器通信但是我无法确定如何将此代码发送的数据限制为单个“hello”,并且还可以防止它丢失最初的2个字符。

NSInputStream *inputStream;
NSOutputStream *outputStream;

-(void)initNetworkCommunication {
    NSLog(@"init net con");
    CFReadStreamRef readStream;
    CFWriteStreamRef writeStream;
    CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"localhost", 6066, &readStream, &writeStream);
    inputStream = (__bridge NSInputStream *)readStream;
    outputStream = (__bridge NSOutputStream *)writeStream;
    [inputStream setDelegate:self];
    [outputStream setDelegate:self];
    [inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream open];
    [outputStream open];
}

-(void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
    case NSStreamEventHasSpaceAvailable: {
        if (stream == outputStream) {
            NSString *res = @"<Hello>";
            NSData *data = [[NSData alloc] initWithData:[res dataUsingEncoding:NSUTF8StringEncoding]];
            [outputStream write:[data bytes] maxLength:[data length]];
            break;
        }
    }
}

0 个答案:

没有答案