我是套接字编程的新手,我参考了http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server,我使用的是PHP服务器,我面对的问题是,我可以使用发送/接收消息插座,但我收到的消息是像我收到的消息打破应该是“你好abcd”,但它给了我“”然后一段时间后“llo”然后一段时间后“abcd”。 我正在使用以下代码来接收消息:使用套接字接收破/不完整的消息
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventNone:
NSLog(@"Stream event none");
break;
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
int len=0;
uint8_t *buffer = (uint8_t *)calloc(1, (16*1024));
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
NSLog(@"byte available %d",len);
if (len > 0) {
NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
//
[data appendBytes:(const void *)buffer length:len];
// NSString *s = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
// NSLog(@"rs %@",s);
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(@"server said: %@", output);
[self messageReceived:output];
}
}
}
}
break;
case NSStreamEventHasSpaceAvailable:
NSLog(@"event space available");
break;
case NSStreamEventErrorOccurred:
NSLog(@"Can not connect to the host!");
break;
case NSStreamEventEndEncountered:
NSLog(@"end");
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[theStream release];
theStream = nil;
break;
default:
NSLog(@"Unknown event");
}
}
我可能是错的,但不应该sizeof(缓冲区)返回指针的大小而不是缓冲区的大小?我的意思是,分配是动态的...另一点,当你分配你的NSMutableData时,为什么当你知道最终长度(len)时,它的长度为0? – 2013-04-22 07:02:13
plz检查这一个http://stackoverflow.com/questions/15583366/tcp-socket-programming-in-ios-server-client-response – 2013-04-22 07:14:41
那么你建议我做什么? @JeromeDiaz – 2013-04-22 07:14:56