iPhoneアプリでは、ソケットを介してサーバーにデータを送信します。アプリはサーバーから回答を受け取る必要があります(問題はサーバー側ではありません)。それが私のコードです:
-(void)sendLocation {
NSLog(@"sendLocation %@, %@", lat, lon);
NSString *imei = @"12345484654";
NSDictionary *sendData = [NSDictionary dictionaryWithObjectsAndKeys:
@"0", @"type",
imei, @"imei",
lat, @"lat",
lon, @"lon",
nil];
NSLog (@"JSON: %@", (NSString*)sendData);
NSString *outJSON = [sendData JSONRepresentation];
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
// CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.36", 12390, NULL, &writeStream);
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.36", 12390, &readStream, &writeStream);
inputStream = (NSInputStream *)readStream;
outputStream = (NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
NSData *data = [[NSData alloc] initWithData:[outJSON dataUsingEncoding:NSASCIIStringEncoding]];
NSString *end = @"\n###";
NSData *endData = [[NSData alloc] initWithData:[end dataUsingEncoding:NSASCIIStringEncoding]];
[outputStream write:[data bytes] maxLength:[data length]];
[outputStream write:[endData bytes] maxLength:[endData length]];
[outputStream close];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[outputStream release];
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode {
NSLog(@"got an event");
switch (eventCode) {
case NSStreamEventHasSpaceAvailable:
NSLog(@"None!");
break;
case NSStreamEventOpenCompleted:
NSLog(@"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (aStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(@"%@",output);
}
}
}
}
[inputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop]forMode:NSDefaultRunLoopMode];
[inputStream release];
break;
case NSStreamEventErrorOccurred:
NSLog(@"CONNECTION ERROR: Connection to the host failed!");
break;
case NSStreamEventEndEncountered:
NSLog(@"Stream Closed");
break;
default:
break;
}
}
ログは私に与えます:
2012-08-22 14:58:52.117 Second[1272:11603] got an event
2012-08-22 14:58:52.117 Second[1272:11603] Stream opened
2012-08-22 14:58:52.117 Second[1272:11603] got an event
2012-08-22 14:58:52.117 Second[1272:11603] None!
では、Inputstreamに何かが起こっているのでしょうか?しかし、何も受け取られませんでした。また、Inputstreamをどこで閉じて解放するかもわかりません。これの何が悪いのかについてのヒントをいただければ幸いです:)