我正在尝试使用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;
}
}
}