我是套接字编程的新手,我通过引用http://www.raywenderlich.com/3932/how-to-create-a-socket-based-iphone-app-and-server来做到这一点,我正在使用 php服务器,我面临的问题是,我可以使用套接字发送/接收消息,但是我收到的消息被破坏了,就像我收到的消息应该是“ Hello 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");
}
}