Maihan Nijat
Maihan Nijat

Reputation: 9344

How to use BufferedReader before PrintWriter in Java

I am working on small Server/ Client application (console base) in Java. The purpose of the application is to send number from client to server and in the server add (+1) with it and return back to client. Client print the line and send back to server the increased number until it reaches 10.

The connectivity between both classes is working properly, but when I put BufferedReader before PrintWriter in server class, then the application doesn't work and also doesn't throws any error.

Client Code:

int count = 1;
PrintWriter out = null;
BufferedReader in = null;

Socket socket = null;

try {
    socket = new Socket("localhost",3700);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new PrintWriter(socket.getOutputStream());    
} catch (UnknownHostException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

while(in.read() != 10){
    out.println(count);
    out.flush();
    System.out.print(in.read());
};

out.close();
in.close();
socket.close();

Server Code:

ServerSocket serverSocket = null;
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
int count = 1;

try {
    serverSocket = new ServerSocket(3700);
} catch (IOException e) {
    e.printStackTrace();
}
try {
    socket = serverSocket.accept();
} catch (IOException e) {
    e.printStackTrace();
}

out = new PrintWriter(socket.getOutputStream());
out.println(count);
out.flush();

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(in.read() != 10){
    count = in.read();
    count++;
};

in.close();
out.close();

serverSocket.close();
socket.close();

Upvotes: 0

Views: 249

Answers (1)

user207421
user207421

Reputation: 310884

while(in.read() != 10){
    count = in.read();
    count++;
};

You are reading characters and throwing them away, and you are ignoring end of stream. It should be:

int ch;
while((ch = in.read()) !- -1 && ch != 10){
    count = ch;
    count++;
};

and similarly for the server side. The -1 test is the end of stream condition, which happens when the peer closes the connection.

But more probably you should be using readLine() and Integer.parseInt():

String line;
while ((line = in.readLine()) != null)
{
    int value = Integer.parseInt(line);
    // etc.
}

Upvotes: 2

Related Questions