我自從算出來並決定回答我自己的問題h只是爲了那些處於類似情況的人的利益。
每當我想給任何字符串,我用我創造了這個輔助函數:
- (void) send:(NSString *)string {
const uint8_t *message = (const uint8_t *)[string UTF8String];
if (_outStream && [_outStream hasSpaceAvailable])
if([_outStream write:message maxLength:strlen((char *)message)] == -1)
NSLog(@"Failed sending data to peer");
}
在接收端,它看起來像這樣:
- (void) stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
if (stream == _inStream) {
// read it in
unsigned int len = 0;
len = [_inStream read:buf maxLength:buffSize];
buf[len] = '\0';
if(!len) {
if ([stream streamStatus] != NSStreamStatusAtEnd)
NSLog(@"Failed reading data from peer");
} else {
NSString *message = [NSString stringWithUTF8String:(char *)buf];
// here you do whatever you need with your received NSString *message
}
}
}
}
緩衝區定義爲:
#define buffSize 60000
uint8_t buf[buffSize];
60,000是相當隨意的,你可以改變它以適應你的需求。
關於上述的幾點說明。儘管爲這些字符串設置相當大的緩衝區是安全的,但您絕對不能保證一次接收字符串。在實際的應用程序中,您應該仔細設計一個可以依賴的特定協議,以檢查是否收到了整個字符串,並在後續NSStreamEvent
s中收到字符串(如有必要)。
我應該只是通過類似 (const uint8_t *)[strBuffer UTF8String]; 其中strBuffer是緩衝區寫入的NSString? – SaltyNuts 2010-06-21 20:10:56