title: iOS Hello World over socket
body: <p>I need to implement simple socket communication (strings) between iOS app and my Java socket server. I manage to connect the two, but I cannot send any messages. Java server is pretty much taken from this <a href="http://zerioh.tripod.com/ressources/sockets.html" rel="nofollow">example</a>, and this is part of my code where I establish connection and (try to) send message to server:</p>
  
  <pre><code>- (void)initNetworkCommunication {
  CFReadStreamRef readStream;
  CFWriteStreamRef writeStream;
  CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)@"192.168.0.10", 2004, &amp;readStream, &amp;writeStream);
  self.inputStream = objc_unretainedObject(readStream);
  self.outputStream = objc_unretainedObject(writeStream);
  [self.inputStream setDelegate:self];
  [self.outputStream setDelegate:self];
  [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  [self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
  [self.inputStream open];
  [self.outputStream open];
  }
  
  - (void)sendMessage {
  NSString *response  = [NSString stringWithFormat:@"aaa"];
  NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
  [self.outputStream write:[data bytes] maxLength:[data length]];
  }
  
  - (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
  
  NSLog(@"stream event %i", streamEvent);
  
  switch (streamEvent) {
  
      case NSStreamEventOpenCompleted:
          NSLog(@"Stream opened");
          break;
      case NSStreamEventHasBytesAvailable:
  
          if (theStream == self.inputStream) {
  
              uint8_t buffer[1024];
              int len;
  
              while ([self.inputStream hasBytesAvailable]) {
                  len = [self.inputStream read:buffer maxLength:sizeof(buffer)];
                  if (len &gt; 0) {
  
                      NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
  
                      if (nil != output) {
  
                          NSLog(@"server said: %@", output);
                          //[self messageReceived:output];
  
                      }
                  }
              }
          }
          break;
  
  
      case NSStreamEventErrorOccurred:
  
          NSLog(@"Can not connect to the host!");
          break;
  
      case NSStreamEventEndEncountered:
  
          [theStream close];
          [theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
          theStream = nil;
  
          break;
      default:
          NSLog(@"Unknown event");
  }
  
  }
  - (IBAction)loginButtonClicked {
  [self initNetworkCommunication];
  [self sendMessage];
  ...}
  </code></pre>