1

在 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。对此有什么问题的提示将不胜感激:)

4

1 回答 1

1

我猜你的代码没有正确地将数据发送到服务器。它首先尝试将数据发送到服务器,因为您释放了它停止工作的输出流。这是我之前为此事件编写的代码。

       case NSStreamEventHasSpaceAvailable: {
                if(stream == outputStream) {

    // str is your string to send the server
        NSData* data = [str dataUsingEncoding:NSASCIIStringEncoding];
        int byteIndex = 0;
        uint8_t *readBytes = (uint8_t *)[data bytes];
        readBytes += byteIndex; // instance variable to move pointer
        int data_len = [data length];
        unsigned int len = ((data_len - byteIndex >= 1024) ?
                            1024 : (data_len-byteIndex));
        uint8_t buf[len];
        (void)memcpy(buf, readBytes, len);
        len = [outputStream write:(const uint8_t *)buf maxLength:len];
        byteIndex += len;
    }
  // release your outputstream
break;
}

我可以为此建议你在同一个地方;

这个地方是用来与 tcp 服务器通信的。

这个地方用于发送和获取 nsstream

最后,我建议您使用 NSJSONSerialization 来处理 json 对象。

于 2012-08-22T16:12:42.787 回答