LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Java bufferedreader -- how to read carriage return/new line sent over network from C (https://www.linuxquestions.org/questions/programming-9/java-bufferedreader-how-to-read-carriage-return-new-line-sent-over-network-from-c-924723/)

texasone 01-19-2012 11:17 PM

Java bufferedreader -- how to read carriage return/new line sent over network from C
 
Basically, I have a server in C that is sending a string of text over the using write. Then I have a client written in Java that is receiving the string and updating the text in a JTextArea. The problem I am having is that when I send the string, all carriage returns or new lines are lost and its just sending it as one long line. Does anyone know how to fix this or a little workaround hack for it?
C server code:
Code:

struct meeting newMeet;
newMeet = agenda();
char * s = NULL;
ticks = time(NULL);
snprintf(buffer, BUFFER_SIZE, "%.24s \r\n%s, %s at %d in %s. %s is on the agenda.\r\n",
ctime(&ticks), newMeet.event, newMeet.day, newMeet.time, newMeet.where, newMeet.agenda);
buffer_length = strlen(buffer);
if (write(connection_handle, buffer, buffer_length) != buffer_length) {
    perror("Write failed");
}

Java Client Code:
Code:

InetAddress serverAddress = InetAddress.getByName(host);
Socket clientSocket = new Socket(serverAddress, port);
InputStream input= clientSocket.getInputStream();

BufferedReader r = new BufferedReader( new InputStreamReader(input));
String s ;
String text = "";
while ( (s = r.readLine()) != null) {
    text = text + s;
}
infoArea.setText(text + "\r\n" + TilMeet);

Let me know if you need the full code. Thanks in advance, RzITex

Nominal Animal 01-20-2012 03:05 AM

Since Java readLine() does not include the newline in the results, you'll need to add it back yourself:
Code:

text = text + s + "\n";
EDIT: As Proud noted below, JTextArea lines should be separated by \n and not by \r\n as I initially had. Thanks, Proud, for the heads-up.

Proud 01-20-2012 08:15 AM

I would suggest the system-specific newline char sequence, but then...
Quote:

Code:

public static String newline = System.getProperty("line.separator");
When NOT to use the system independent newline characters

JTextArea
lines should be separated by a single '\n' character, not the sequence that is used for file line separators in the operating system.

Console output (eg, System.out.println()), works fine with '\n', even on Windows.


All times are GMT -5. The time now is 03:22 PM.