Cannot receive from client socket in a loop [duplicate] - java

This question already has answers here:
Java - Understanding PrintWriter and need for flush
(2 answers)
Closed 6 years ago.
I am trying to make a simple quiz between client and server. The server sends an array of questions and waits for a reply from client. The problem is that the client side does not display the array from server nor can take any input. The server has definitely connected to the client, but the client side stays idle.
Server:
OutputStream o =sock.getOutputStream();
PrintWriter pw = new PrintWriter(o);
InputStream is = sock.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
int i=0;
while(i<10)
{
pw.println(array[i]);
String st = br.readLine();
System.out.println(st);
i++;
}
Client:
InputStream istream = sock.getInputStream();
BufferedReader content = new BufferedReader(new InputStreamReader(istream));
String str;
OutputStream ostream=sock.getOutputStream();
PrintWriter pw = new PrintWriter(ostream)
String ans;
for(int j=0;j<10;j++)
{
str=content.readLine();
System.out.println(str);
ans=sc.nextLine();
pw.println(ans);
}

PrintWriter#println doesn't flush text to client by default so you need to call pw.flush() manually each time you want to ensure sending.
To let println automatically flush text to client use PrintWriter(Writer out, boolean autoFlush) constructor with autoFlush parameter set as true, like
PrintWriter pw = new PrintWriter(o, true);
since PrintWriter(OutputStream out) constructor internally invokes this(out, false); so automatic flash is disabled println, printf or format methods.

PrintWriter doesn't flush information itself by default.
You should either add: pw.flush() after pw.println(ans) or create your writer in that way: PrintWriter pw = new PrintWriter(o, true);

Related

How do I know If client wants to send the data or recieve the data from server

when I am trying to send the data from the server, my client side is not able to receive the data. The server is able to write the data to the JSON file. I think because I am executing the code for sending and receiving the data on the server inside the main method every time regardless of what request I am receiving from the client. Is there any built-in method in Java that helps us know what the client request is and execute the codes on the server depending on the request rather than executing the code for both read and write request. I hope You guys understand.
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(666);
FileReader fileReader = new FileReader("MYJSON.json");
BufferedReader buff = new BufferedReader(fileReader);
while(true) {
Socket socket = serverSocket.accept();
InputStreamReader inputStreamReader = new
InputStreamReader(socket.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = bufferedReader.readLine();
writeJson(str);
String str;
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(socket.getOutputStream());
PrintWriter printWriter = new PrintWriter(outputStreamWriter);
str = buff.readLine();
printWriter.write(str);
printWriter.flush();
printWriter.close();
}
}

BufferedReader readLine() have weird characeters

I have found a issue when I write and read data from sockets, in this time the socket are already open.
The code from server:
<pre>ServerSocket server = new ServerSocket(2001);
Socket socket = server.accept();
while(true){
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String readString = br.readLine();
System.out.println("result:\n"+readString)
}</pre>
The test I made from a client
<pre>Socket socket = new Socket("localhost", 2001);
Scanner consoleRead= new Scanner(System.in);
consoleRead.useDelimiter("\n");
ObjectOutputStream oo = new ObjectOutputStream(socket.getOutputStream());
while(true){
String s = consoleRead.next();
oo.writeUTF(s+System.lineSeparator());
oo.flush();
}</pre>
The first line is read perfectly... But the rest begin with weird characters.
Regards
If you are writing with ObjectOutputStream then read with ObjectInputStream insted of InputStreamReader
writeUTF()
Primitive data write of this String in modified UTF-8 format. Note that there is a significant difference between writing a String into the stream as primitive data or as an Object. A String instance written by writeObject is written into the stream as a String initially. Future writeObject() calls write references to the string into the stream.
Better is :- Write with OutputStreamWriter and read with InputStreamReader
For better understanding:- write the same thing in a file with ObjectOutputStream and then check what is getting written.

Can't use InputStream from Socket after writeObject

Here is the situation:
I have a ServerSocket ss, and "Socket socket = ss.accept();", then if I do this:
istream = socket.getInputStream();
ostream = socket.getOutputStream();
in = new BufferedReader(new InputStreamReader(istream));
out = new PrintWriter(new BufferedOutputStream(ostream));
/*
I use in/out few times
everything OK
*/
ObjectOutputStream oos = new ObjectOutputStream(ostream);
oos.writeObject(someobject);
/* probably code that solves the problem */
String line = in.readLine();
On the client side I have this code:
PrintWriter out = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()),true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
/*
using in/out, no problems
*/
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
SomeObject so = (SomeObject)ois.readObject();
out.println("some text");
Everything is OK, until I send someobject. Client recieves object properly, no problems there. But I can't use socket anymore. If I do oos.close(), I get Exception that says "socket closed". If I do oos.reset() I get Exception with similar message. "socket reset". So what should I do? Is it possible to use same input and output streams after writeObject()?
What happens when I send "some text" is that I'm just getting nulls no matter how many times I call readLine(), I never get that "some text".
You can't use multiple type of stream/reader/writer on the same underlying socket. All your streams and readers and writers are buffered so they will all get thoroughly mixed up. Stick tone kind. Stick to one protocol. If you have object streams, use them for everything. And create them once for the life of the socket, not per message.

Why does flush() effect println() on PrintWriter

I have the basic code for a server:
ServerSocket serverSocket = new ServerSocket(14000);
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
String incoming;
while((incoming = in.readLine()) != null){
System.out.println("Client Says: " + incoming);
out.println("Client Says: " + incoming);
out.flush();
//if(incoming.equals("HELLO")) break;
}
clientSocket.close();
serverSocket.close();
I'm trying to further understand streams as they're giving me some serious headaches. From what I've read, println methods automatically flush for you, however this line is not delivered to the client unless the flush method is called afterwards? I'm just looking for a nice solid explanation of this?
To enable automatic flushing of the PrintWriter, the second argument of its constructor must be set to true.
I had this issue before, just:
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
That will make the difference. If you do not autoflush you can get some errors or receive data as null, it happened to me some time ago. Best regards.

Java socket reading issue when receives 0

I'm trying to communicate between 2 programs in Java with Java Sockets. I want to send some bytes through the socket as Data. Those bytes being data, their value can be anything (so could be 0 and possibly -1). I tried to use the DataInputStream class to handle the communications and works fine if i don't receive the byte 0 somewhere in the bytes i am trying to read, otherwise, it seems to block at this 0 byte and stop reading. Any one would have any ideas on the how or why this is happening and any ideas on how to work this around ? Thanks !
Please keep it simple,
Try using InputStream, InputStreamReader, BufferedReader, OutputStream, PrintWriter.
Client Side:
Socket s = new Socket();
s.connect(new InetSocketAddress("Server_IP",Port_no),TimeOut);
// Let Timeout be 5000
Server Side:
ServerSocket ss = new ServerSocket(Port_no);
Socket incoming = ss.accept();
For Reading from the Socket:
InputStream is = s.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
boolean isDone = false;
String s = new String();
while(!isDone && ((s=br.readLine())!=null)){
System.out.println(s); // Printing on Console
}
For Writing to the Socket
OutputStream os = s.getOuptStream();
PrintWriter pw = new PrintWriter(os)
pw.println("Hello");

Categories

Resources