有没有人在通过EASession处理配件时如何处理Monotouch中的读写NSStream事件?
看起来没有一个强类型的委托,我在找出我需要处理的InputStream和OutputStream委托的选择器以及我实际需要对每个选择器按顺序执行的操作时遇到问题正确填充和清空属于EASession对象的缓冲区。
基本上,我正在尝试将Apple的EADemo应用程序移植到Monotouch。
以下是我认为与此问题相关的Objective-C来源:
/
/ asynchronous NSStream handleEvent method
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
switch (eventCode) {
case NSStreamEventNone:
break;
case NSStreamEventOpenCompleted:
break;
case NSStreamEventHasBytesAvailable:
[self _readData];
break;
case NSStreamEventHasSpaceAvailable:
[self _writeData];
break;
case NSStreamEventErrorOccurred:
break;
case NSStreamEventEndEncountered:
break;
default:
break;
}
}
/ low level write method - write data to the accessory while there is space available and data to write
- (void)_writeData {
while (([[_session outputStream] hasSpaceAvailable]) && ([_writeData length] > 0))
{
NSInteger bytesWritten = [[_session outputStream] write:[_writeData bytes] maxLength:[_writeData length]];
if (bytesWritten == -1)
{
NSLog(@"write error");
break;
}
else if (bytesWritten > 0)
{
[_writeData replaceBytesInRange:NSMakeRange(0, bytesWritten) withBytes:NULL length:0];
}
}
}
// low level read method - read data while there is data and space available in the input buffer
- (void)_readData {
#define EAD_INPUT_BUFFER_SIZE 128
uint8_t buf[EAD_INPUT_BUFFER_SIZE];
while ([[_session inputStream] hasBytesAvailable])
{
NSInteger bytesRead = [[_session inputStream] read:buf maxLength:EAD_INPUT_BUFFER_SIZE];
if (_readData == nil) {
_readData = [[NSMutableData alloc] init];
}
[_readData appendBytes:(void *)buf length:bytesRead];
//NSLog(@"read %d bytes from input stream", bytesRead);
}
[[NSNotificationCenter defaultCenter] postNotificationName:EADSessionDataReceivedNotification object:self userInfo:nil];
}
我也很欣赏任何关于如何在monotouch中最好地实现这一点的架构建议。例如,在Objective C实现中,这些函数不包含在任何类中 - 但是在Monotouch中使它们成为我的成员是有意义的
答案 0 :(得分:0)
看起来MonoTouch的最新版本(我必须首先升级到iOS 4.2才能获得它)现在实现了HandleEvent的强类型委托和新的NSStreamEvent类型,因此它可以更容易处理:
// asynchronous NSStream handleEvent method
public override void HandleEvent (NSStream theStream, NSStreamEvent streamEvent)
{
switch (streamEvent)
{
case NSStreamEvent.None:
break;
case NSStreamEvent.OpenCompleted:
break;
case NSStreamEvent.HasBytesAvailable:
LowReadData((NSInputStream)theStream);
break;
case NSStreamEvent.HasSpaceAvailable:
LowWriteData((NSOutputStream)theStream);
break;
case NSStreamEvent.ErrorOccurred:
break;
case NSStreamEvent.EndEncountered:
break;
default:
break;
}
}