Question

I am sending a Text from Xcode (that a user enters on a textView) to java server. the text may contain more than one line. the problem is when receiving the text, only even lines are being read. here is my code.

server:

            StringBuilder sb = new StringBuilder();
            while(inFromClient.readLine()!=null){   //infromClient is the buffered reader

                sb.append(inFromClient.readLine());
                sb.append('\n');
            }
            System.out.println ("------------------------------");
            System.out.println (sb.toString()); //the received text

client side:

           NSString *notecontent=[NSString  stringWithFormat:@"%@",self.ContentTextView.text];
        NSData *notecontentdata = [[NSData alloc] initWithData:[notecontent dataUsingEncoding:NSASCIIStringEncoding]];
        [outputStream write:[notecontentdata bytes] maxLength:[notecontentdata length]];
Was it helpful?

Solution

You're consuming three lines:

  1. Check if there's next line
  2. Printing line
  3. Storing one.

Noted here:

while(inFromClient.readLine()!=null) { //1.
    System.out.println (inFromClient.readLine()); //2.
    sb.append(inFromClient.readLine()); //3.
    sb.append('\n');
}

Store the line in a String and then do what you want/need with it:

String line = "";
while ((line = inFromClient.readLine()) != null) {
    System.out.println(line);
    sb.append(line);
    sb.append('\n');
}

OTHER TIPS

I think the issue is this:

while(inFromClient.readLine()!=null){   //infromClient is the buffered reader
    System.out.println (inFromClient.readLine());
    sb.append(inFromClient.readLine());
    sb.append('\n');
}

The issue, specifically, is the three readLine() calls. Each call will read another line from the client. So effectively you're reading a line to check if the client has stuff to send, reading another line and printing printing it, then reading another and storing it.

What you want to do is store the read line in a temp variable, print it, then append it:

String s;
while((s = inFromClient.readLine()) !=null){   //infromClient is the buffered reader
    System.out.println (s);
    sb.append(s);
    sb.append('\n');
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top