我从 Apple 的网站下载了 WiTap代码。它用于通过本地 wifi 网络传输数据。我正在一个项目中作为客户端 - 服务器架构进行交互。我正在将 NSData 从客户端发送到服务器。
我做了2个项目;一个用于客户端,一个用于服务器
在客户端项目中,我进行了以下更改为此我通过添加以下方法修改了AppController.m文件
AppController.m(客户端)
- (void)sendData:(NSData*)pobjData
{
assert(self.streamOpenCount == 2);
if ( [self.outputStream hasSpaceAvailable] )
{
NSInteger bytesWritten;
NSUInteger length = [pobjData length];
bytesWritten = [self.outputStream write:[pobjData bytes] maxLength:[pobjData length]];
NSLog(@"written bytes -> %d",bytesWritten);
}
}
然后通过调用这个方法我发送数据。
在服务器端项目中,我通过修改以下方法修改了 AppController.m 文件。
AppController.m(服务器端)
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
#pragma unused(stream)
switch(eventCode) {
case NSStreamEventOpenCompleted: {
self.streamOpenCount += 1;
assert(self.streamOpenCount <= 2);
// Once both streams are open we hide the picker and the game is on.
if (self.streamOpenCount == 2) {
[self dismissPicker];
[self.server deregister];
}
} break;
case NSStreamEventHasSpaceAvailable: {
assert(stream == self.outputStream);
// do nothing
} break;
case NSStreamEventHasBytesAvailable:
{
if (stream == self.inputStream)
{
NSInteger bytesRead;
uint32_t buffer[32768];
NSMutableData *_data = [NSMutableData data];
// Pull some data off the network.
bytesRead = [self.inputStream read:buffer maxLength:sizeof(buffer)];
if (bytesRead == -1) {
} else if (bytesRead == 0) {
} else {
// FIXME: Popup an alert
const long long expectedContentLength = bytesRead;
NSUInteger expectedSize = 0;
// expectedContentLength can be represented as NSUInteger, so cast it:
expectedSize = (NSUInteger)expectedContentLength;
[_data appendBytes:buffer length:expectedSize];
NSLog(@"\"Data received has length: %d", _data.length);
[self performSelector:@selector(getData:) withObject:_data afterDelay:1.0];
}
}
}
break;
default:
assert(NO);
// fall through
case NSStreamEventErrorOccurred:
// fall through
case NSStreamEventEndEncountered: {
[self setupForNewGame];
} break;
}
}
并添加了将接收到的数据写入文件的方法
#define kUserDirectoryPath NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
-(void)getData:(NSMutableData *)pData
{
NSFileManager *tmpmanager = [NSFileManager defaultManager];
[tmpmanager createFileAtPath:[AppController getDocumentDirectoryPath:[NSString stringWithFormat:@"%@.png",[NSDate date]]] contents:pData attributes:nil];
}
+(NSString*)getDocumentDirectoryPath:(NSString*)pStrPathName
{
NSString *strPath=nil;
if(pStrPathName)
strPath = [[kUserDirectoryPath objectAtIndex:0] stringByAppendingPathComponent:pStrPathName];
return strPath;
}
我将 .png 文件转换为 NSData 并将它们从客户端发送到服务器端。服务器将文件下载到文档目录
问题是,当我从客户端传输文件时,它会在文档目录中下载到服务器端。在小文件的情况下一切正常。如果文件大小超过 8kB ,则写入文档目录的文件会损坏。
请帮助我能够发送大文件。