Why does my Printwriter not work like i want? - java

I have a Problem with my Printwriter in some of my Projects. I always have to close it because otherwise the send message of the Serversockets doesn´t come to the wished server.
Socket socket = serverSocket.accept();
console.writeMessageinConsole("Client"+socket.getInetAddress()+" verbindet!");
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
PrintWriter printWriter = new PrintWriter(outputStream, true);
System.out.println("da");
printWriter.write("dadad");
printWriter.close();
Can you plase help me?

The only reason to use a BufferedWriter is to buffer the output. If you want to send immediately, don't use buffering.
The only reason to use a PrintWriter is to add println and printf. If you want to use write() you don't need a PrintWriter.
So you can either;
drop the BufferedWriter.
use println, or
flush() the output

Related

PrintWriter vs BufferedWriter

I'm trying to transfer strings from my server to my client and I'm trying to find an explanation why when I'm using PrintWriter in my server the client receives the string while when I'm using BufferedWriter the client doesn't receive the string.
In my client I have the next readers/writers:
out=new PrintWriter(s.getOutputStream());
in=new BufferedReader(new InputStreamReader(s.getInputStream()));
In my main I'm receiving data from server with the next call:
String sol=in.readLine();
In my server I'm sending data with the next call (os is an outputStream that I get in my function):
PrintWriter out= new PrintWriter(os);
out.write("test");
out.flush();
While when I use BufferedWriter it doesn't send data to the client (or the client can't receive it?) "
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(os));
out.append("test"); // tried also using out.write
out.flush();
On my server side Bufferwriter doesn't add "\n" to the end of the string while in my client side I'm trying to read a line with inputstream. Printwriter adds "\n" in the method println. Thanks to #EdwinDalorzo for the help.

Java sockets - Why do I need a PrintWriter to make this work?

I'm trying to learn socket programming in Java but unfortunately I'm running into some behaviour that I don't understand. I have a very simple client program that connect to a server socket and sends some text that gets echoed back. Said client program looks like this:
try(
Socket socket = new Socket("127.0.0.1", 5001);
OutputStreamWriter writer = new OutputStreamWriter(socket.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
){
String userInput = "";
while (!userInput.toLowerCase().equals("quit")) {
userInput = stdIn.readLine();
writer.write(userInput);
writer.flush();
System.out.println("Server response: " + reader.readLine());
}
}
catch(Exception e) {e.printStackTrace();}
When I run this program the first line that I enter gets sent to the server but after that I can enter as many lines as I want and nothing gets sent. I also never see anything printed out by the System.out.println() line.
But if I switch out the OutputStreamWriter for a PrintWriter everything works as it should! Here's the code with PrintWriter:
try(
Socket socket = new Socket("127.0.0.1", 5001);
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
){
String userInput = "";
while (!userInput.toLowerCase().equals("quit")) {
userInput = stdIn.readLine();
writer.println(userInput);
System.out.println("Server response: " + reader.readLine());
}
}
catch(Exception e) {e.printStackTrace();}
Anyone have any idea why the first of the above two programs acts weird while the second one works? If anyone can tell me what the difference between writing with an OutputStreamWriter vs a PrintWriter is then that might tell me what's going on.
Note that the difference between write() and println() is that println() adds a linebreak after the data while write() does not.
So if your server uses readLine() to receive the data with a client using write() it might wait forever for the end of the line to read without receiving it.
So writer.write(userInput + "\n") might do the trick.

BufferedWriter isn't accepting second input from client?

I have a server and client application. They both use a BufferedWriter-InputStreamReader-InputStream to read information coming from the server, or coming from the client
I have it working so I can use
bw.write("command");
to execute a command on the server side, and output the information back to the client-side.
However, I am running into trouble doing it twice, for two different commands. Here's the code:
Server-sided code:
public void run() {
try {
while (true) {
socket.setTcpNoDelay(true);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String input = br.readLine();
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
if (input.equals("increment")) {
bw.write(String.valueOf(totalBets.incrementAndGet()));
bw.newLine();
bw.flush();
} else if(input.equals("generate")) {
Random rand = new Random();
bw.write(String.valueOf(rand.nextDouble()*99));
bw.newLine();
bw.flush();
}
}
}
Client-sided code:
public void actionPerformed(ActionEvent arg0) {
try {
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
bw.write("increment" + "\n");
bw.flush();
String id = br.readLine();
bw.write("generate");
bw.flush();
String roll = br.readLine();
}
}
The first String id gets the output from running the bw.write("increment"), but when I try to run bw.write("generate"), it freezes when running the line: String roll = br.readLine();
Any help?
Thank you!
I suggest that you use PrintWriter rather than BufferedWriter. Use BufferedReader to read without leaving data in the underlying operating system's buffers, so they will be buffered at application level, but for writing you want it to go out as soon as you send one complete 'command'.
With a PrintWriter you can also use println which should solve your problem.
You're losing data, or risking it, by creating multiple BufferedReaders. Use the same one for the life of the socket. Ditto the BufferedWriter.

Can one write to a wrapped Stream in java?

I'm writing a java server for an assignment, and I have observed some strange behaviour when I write both into a wrapped stream and a wrapper stream, can this cause any problems ? As far as I see, it can, but how ? Pls enlighten me.
as an example:
OutputStream os = new OutputStream(...);
PrintWriter pw = new PrintWriter(os);
And I want to write both in the PrintWriter, and the OutputStream.
To transfer from byte-based stream to character-based stream, you need to use OutputStreamWriter:
An OutputStreamWriter is a bridge from character streams to byte streams.
So that would be:
OutputStream os = ...
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
PrintWriter pw = new PrintWriter(osw);
I think the problem is that you need to specify the encoding, since the constructor PrintWriter(OutputStream out) uses the default encoding which might not be correct for your data input:
OutputStream os = ...
PrintWriter pw = new PrintWriter(os, "UTF-8");

how does the getOutputStream() of Socket work?

{ Socket s = new Socket("xxx.xx.xx.xx",10004);
BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
PrintWriter out = new PrintWriter(s.getOutputStream(),true);
BufferedReader bufIn = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while((line=bufr.readLine())!=null){
if("over".equals(line))
break;
out.println(line);
String upperStr = bufIn.readLine();
System.out.println(upperStr);
}
s.close();}
so does the out.println(line); mean 1. the string which was entered will appear on the screen and 2.the content will be sent to the server socket at the same time? Thanks, guys.
Your variable out is a PrintWriter, but that doesn't mean that its something that will be printed on the screen. In this case, you gave it something that is the output stream of a socket, so it will print a line to the socket. If you want it to appear on the screen as well, you'll have to call something like System.out.println(line) as well.

Categories