Java socket can't reply outside of the loop - java

I have a Java server that listens to connections from a PHP client and replies back. My problem is I can't write anything to outputStream after reading the inputStream.
while (true)
try {
clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(2000);
if (!clientSocket.getInetAddress().equals(clientSocket.getLocalAddress())) {
clientSocket.close();
continue;
}
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
LinkedList<String> messageFromPHP = new LinkedList<>();
String message = "";
while ((message = br.readLine()) != null)
messageFromPHP.add(message);
bw.write("test_message\n");
bw.flush();
bw.close();
br.close();
clientSocket.close();
} catch (SocketTimeoutException ex) {
} catch (IOException ex) {
ex.printStackTrace();
serverSocket.close();
}
^^ This makes both the PHP client and Java Server stuck forever. (I have added SoTimeout to the server to prevent that)
while (true)
try {
clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(2000);
if (!clientSocket.getInetAddress().equals(clientSocket.getLocalAddress())) {
clientSocket.close();
continue;
}
BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));
LinkedList<String> messageFromPHP = new LinkedList<>();
String message = "";
while ((message = br.readLine()) != null) {
messageFromPHP.add(message);
bw.write("test_message\n");
bw.flush();
}
bw.close();
br.close();
clientSocket.close();
} catch (SocketTimeoutException ex) {
} catch (IOException ex) {
ex.printStackTrace();
serverSocket.close();
}
^^ However this one works perfectly fine and I don't know why. I'm sure these while loops end because I can print messageFromPHP without a problem with both codes.
So, how can I avoid doing everything inside the readLine loop?
Edit: To make things more clear: I want to write and read like the first code. But when I'm reading the input, I can't write to output so I have to use the second code and I don't want to. I'm trying to store the input inside the messageFromPHP list and write to output after that according to the input in the list.

Related

Error in sending bytes in java: buffered reader and input stream

I am trying to send a json string from a client to a server. The code seems to send the string correctly from the client, but the server won't receive the code and print out the results. What am I doing wrong?
InputStream inp;
PrintStream ps = null;
while(true){
try{
ps = new PrintStream(socket.getOutputStream());
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
System.out.println("hello"); //This works
String input = brinp.readLine();
System.out.println(input); //Nothing is printed here
}
catch(IOException e){
System.out.println(e);
}
}
This is my server side code
//Socket s was initialized above
BufferedReader br;
DataOutputStream dos;
try {
dos = new DataOutputStream(s.getOutputStream());
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PatientStructure patient = new PatientStructure((int) (Math.random() * 10 + 1),
textFieldFirstName.getText(), textFieldLastName.getText(), new String[1]);
String sendString = gson.toJson(patient);
dos.writeBytes(sendString);
System.out.println("hello"); //This runs so my guess is that the above line has worked correctly
/**if (br.readLine().equals("ACCEPTED"))
dos.writeBytes(sendString + "/n");
else
System.out.println("Error");**/
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Both programs are connected to the same socket and problem seems to be in these lines. Thanks in advance :)

How to use BufferedReader to read content in DataInputStream

I wrote a simple socket tutorial about sending/receive messages between client and server. I used DataOutputStream to write the string in stream but server couldn't read it if I used BufferedReader
If I use PrintWriter to write(client side), it works.
What's wrong here? Tks so much.
1. Client:
client = new Socket("localhost", 1982);
DataOutputStream opStr = new DataOutputStream(client.getOutputStream());
//pw = new PrintWriter(client.getOutputStream(), true);
//pw.println("Hello, is there anybody out there?");// Can be read by BufferedReader
opStr.writeUTF("Hello, anyone there?");
opStr.flush();// BufferedReader can't read it
2. Server:
openServer();// port 1982
while(true) {
Socket clientSocket = null;
// listen to connection.
clientSocket = echoServer.accept();
DataInputStream inStr = new DataInputStream(
clientSocket.getInputStream());
//System.out.println("M1: Got msg " + inStr.readUTF());// It showed the content
BufferedReader bfReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("got Messages: ");
String strLine = "";
// Don't show anything
while ((strLine = bfReader.readLine()) != null) {
System.out.println(strLine);
}
}
You can't. If you use writeUTF() at one end, you have to use readUTF() at the other end.
You just have to decide which API you're going to use, instead of trying to mix and match them.
You want to read the files as either text e.g. BufferedReader OR binary e.g. DataInputStream. So you can't use both.
Server.java
public class Server
{
public static void main(String[] args)
{
DataInputStream inStr = null;
String str;
openServer();// port 1982
while(true)
{
Socket clientSocket = null;
// listen to connection.
clientSocket = echoServer.accept();
try
{
inStr = new DataInputStream(clientSocket.getInputStream());
str = inStr.readUTF();
System.out.print((String) str);
System.out.flush();
}
catch (IOException io)
{
System.err.println("I/O error occurred: " + io);
}
catch (Throwable anything)
{
System.err.println("Exception caught !: " + anything);
}
finally
{
if (inStr != null)
{
try
{
inStr.close();
}
catch (IOException io)
{
System.err.println("I/O error occurred: " + io);
}
}
}
}
}
}

Message not sending to Server from Client - Java

I have a Server-Client program where I send a small messsage to the client using JLabel. When that message is recieved from server that particular client must send a response immediately. But it is not sending any message . Can somebody look at my code and tell me where my mistake is?
//SERVER
void connect_clients()
{
try {
ServerSocket listener = new ServerSocket(7700);
jButton1.setText("Server Running!");
jButton1.setEnabled(false);
while (true) {
socket = listener.accept();
socketList.add(socket);
//socketList.add(listener.accept());
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);
}
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(null,ex);
}
}
//CLIENT
void connect_server() throws IOException
{
try {
// TODO code application logic here
String serverAddress = JOptionPane.showInputDialog(
"Enter IP Address of a machine that is\n" +
"running the date service on port 9090:");
s = new Socket(serverAddress, 7700);
while(true){
BufferedReader input =
new BufferedReader(new InputStreamReader(s.getInputStream()));
String answer = input.readLine();
System.out.println(answer);
if(answer != null)
{
PrintStream pr = new PrintStream(s.getOutputStream());
InputStreamReader rd = new InputStreamReader(System.in);
BufferedReader ed = new BufferedReader(rd);
String temp = ed.readLine();
pr.println(temp);
JOptionPane.showMessageDialog(null,"Answer is not null"); //THIS WORKS
}
}
}
catch (ConnectException e) {
JOptionPane.showMessageDialog(null, e);
}
catch (SocketException e) {
JOptionPane.showMessageDialog(null, e);
}
}
Some points that you missed in your implementation:
the streams and sockets are never closed
in the client i do not see the point of the endless loop
the client should initialize the communication by sending a message via output stream (not to try to read first)
For a simple example the steps should be:
Start sever to listen and once a connection is established to read the message (you did)
The client should sent a message via output stream and close the steams and the socket
The severs should close the streams and the sockect for the established connection
Example:
//Server
socket = listener.accept();
BufferedReader ed = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream());
String tmp = ed.readLine();
System.out.print("I Recieved :"+tmp);
String msg = "Message received";
pr.write(msg,0,msg.length());
pr.newLine();
ed.close();
pr.close();
socket.close();
//Client
BufferedWriter pr = new BufferedWriter(new OutputStreamWriter(s.getOutputStream());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String sendMessage = "Send Message";
pr.write(msg,0,msg.length());
pr.newLine();
String answer = input.readLine();
System.out.println(answer);
JOptionPane.showMessageDialog(null,"Answer is not null");
input.close();
pr.close();
s.close();
UPDATE
reading from input stream continuously:
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line;
while((line=input.readLine())!=null){
//do something with line
}
I will suggest a simple approach where server is sending the hi msg to client.
For server:
//Server
ServerSocket ss=new ServerSocket(3554);
socket = ss.accept();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getOutputStream()));
String msg ="Hi from server"
bw.write(msg);
String msgFromClient=br.readLine();
System.out.println(msgFromClient);
bw.close();
socket.close();
For Client:
//Client
Socket socket=new Socket("localhost",3554)
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
String received = input.readLine();
System.out.println(received);
bw.write("Client recieve :"+received);
br.close();
bw.close();
socket.close();

Read an UTF-8 encoded text file from internet in Java

I want to read an xml file from the internet. You can find it here.
The problem is that it is encoded in UTF-8 and I need to store it into a file in order to parse it later. I have already read a lot of topics about that and here is what I came up with :
BufferedReader in;
String readLine;
try
{
in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
BufferedWriter out = new BufferedWriter(new FileWriter(file));
while ((readLine = in.readLine()) != null)
out.write(readLine+"\n");
out.close();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
This code works until this line : <title>Chérie FM</title>
When I debug, I get this : <title>Ch�rie FM</title>
Obviously, there is something I fail to understand, but it seems to me that I followed the code saw on several website.
This file is not encoded as UTF-8, it's ISO-8859-1.
By changing your code to:
BufferedReader in;
String readLine;
try
{
in = new BufferedReader(new InputStreamReader(url.openStream(), "ISO-8859-1"));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file) , "UTF-8"));
while ((readLine = in.readLine()) != null)
out.write(readLine+"\n");
out.flush();
out.close();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
You should have the expected result.
If you need to write a file in a given encoding, use FileOutputStream instead.
in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
FileOutputStream out = new FileOutputStream(file);
while ((readLine = in.readLine()) != null)
write((readLine+"\n").getBytes("UTF-8"));
out.close();

Will setting a timeout on a socket work if you are reading a full line using a buffered reader?

I'm writing a socket client that sends a line down a socket connection and then waits for up to 45 seconds for a line back from the server.
I'm using a buffered reader like so:
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
socket = new Socket(host, 800);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
} catch (UnknownHostException e) {
listener.failedToConnectToHost(e);
return;
} catch (IOException e) {
listener.failedToConnectToHost(e);
return;
}
BufferedReader stdIn = new BufferedReader(
new InputStreamReader(System.in));
out.println("message");
try {
String response = in.readLine();
listener.responseRecived(response);
return;
} catch (IOException e) {
listener.errorReadingResponse(e);
return;
}
If I add the following line (Or something like it)
socket.setSoTimeout(45000);
What will happen after 45 seconds assuming that nothing has come through from the other end?
I assume I'll be catching an interrupted exception but I'm sure?
Will this even work? The docs for setSOTImeOut() imply that it's socket.read() that will timeout, I assume that the buffered reader is calling this somewhere down the stack, but assumption is the mother of all screw ups, so I just wanted to check.
The BufferedReader.readLine() method will throw a SocketTimeoutException after 45 seconds.
Apparently it does work and you get a SocketTimeoutException.

Categories