Client application socket closed after printing string - java

I'm building a Java client application which needs to send a message to a server and receive a response afterwards. I can send the message successfully, the problem is that I can't get the response because I get an IO exception ("Socked is closed") when trying to read the 'BufferedReader'.
This is my code, so far:
public class MyClass {
/**
* #param args the command line arguments
*/
#SuppressWarnings("empty-statement")
public static void main(String[] args) {
JSONObject j = new JSONObject();
try {
j.put("comando", 1);
j.put("versao", 1);
j.put("senha", "c4ca4238a0b923820dcc509a6f75849b");
j.put("usuario", "1");
j.put("deviceId", "1");
} catch (JSONException ex) {
System.out.println("JSON Exception reached");
}
String LoginString = "{comando':1,'versao':1,'senha':'c4ca4238a0b923820dcc509a6f75849b','usuario':'1','deviceId':'1'}";
try {
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket("10.1.1.12", 3333);
System.out.println("Connected to the server successfully");
PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(),true);
outToServer.println(j.toString());
outToServer.close();
System.out.println("TO SERVER: " + j.toString());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
String resposta = inFromServer.readLine();
System.out.println("FROM SERVER: " + resposta);
clientSocket.close();
} catch (UnknownHostException ex) {
System.out.println("Could not connect to the server [Unknown exception]");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
I know that the socket is being closed because of the OutToServer.close() but closing the stream is the only way to send the message. How should I approach this situation?

flush() is not the case when it comes with new PrintWriter(, true).
The real problem is that you are closing the PrintWriter outToServer which wraps the underlying InputStream, again, came from the Socket.
When you close the outToServer you're closing the whole socket.
You have to use Socket#shutdownOutput().
You don't even have to close the output if you want to keep the socket's in/out channels for further communications.
flush() when you are done with any writeXXX. Those writeXXX practically don't mean you sent those bytes and characters to other side of the socket.
You may have to close the output, and output only, to signal the server that you sent all you had to send. This is really a matter of the server-side socket's desire.
final Socket socket = new Socket(...);
try {
final PrintStream out = new PrintStream(socket.getOutputStream());
// write here
out.flush(); // this is important.
socket.shutdownOutput(); // half closing
// socket is still alive
// read input here
} finally {
socket.close();
}

Try to call outToServer.flush()
That will try to flush the data from the buffer, although it still not guarantees that it will be sent.

Related

readLine of socket input stream causes hang in socket

hi I have an application that sends text to a device and the device shows it on a display. for transferring data I'm using socket in a AsyncTask class
try {
Socket socket = new Socket(DISPLAY_IP, DISPLAY_PORT);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(params[0]);
output.flush();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
the problem is I can't read response from socket after sending data. when I'm getting input stream from socket and reading line I'm not getting anything and the device is not showing the sent data from me till I close the application so I think the socket is blocking when I'm doing that
try {
Socket socket = new Socket(DISPLAY_IP, DISPLAY_PORT);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println(params[0]);
output.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String response = bufferedReader.readLine();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
how can I send data and read response from socket?
You are trying to communicate with two (client) Sockets. For communication you must implement on one side a (client) java.net.Socket and on the other a java.net.ServerSocket.
You may read further here.
What are you trying to achieve?
When using InputStream it will get data that came from other side, not the data that you just sent.
And as SirGregg said readLine will hang until the whole line is received.

My java chat client only sends strings when the dataStream is closed

I created a java chat application (client and server)
Everything works fine when I'm on my LAN (using LAN IP address of the server into my client).
But when I'm using the Internet address of my server in my client, the strings are sent only when I close the output Data stream of my client (and all the strings are sent at once).
Here's a quick snap of my code (I have port forward from 6791 to 6790 in the example below),
My server (thread):
// this line is actually on my global server class, used below with theServer
ServerSocket svrSocket= new ServerSocket(6790);
//wait for incoming connection
connectionSocket = svrSocket.accept();
connectionSocket.setSoTimeout(10000);
// free the accepting port
svrSocket.close();
//create a new thread to accept future connections (creates a new svrSocket)
theServer.openNewConnection();
//create input stream
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
boolean threadRunning = true);
while (threadRunning) {
//System.out.println("thread: in the while");
try {
Thread.sleep(100);
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
}
catch...
}
My client:
InetAddress dnsName;
Socket clientSocket;
PrintWriter out;
dnsName = InetAddress.getByName("myAddress.me");
clientSocket = new Socket(dnsName.getHostAddress(), 6791);
Thread.sleep(10);
out = new PrintWriter(clientSocket.getOutputStream(), true );
int i=140;
while (i>130){
try {
out.println(Integer.toString(i));
out.flush();
Thread.sleep(200);
}
catch(Exception e) {
e.printStackTrace();
}
i--;
}
out.flush();
out.close();
clientSocket.close();
I've tried with DataOutStreams, there's nothing to do.
My server will only receive the strings when out.close() is called on client side.
Is there a reason why, over the Internet, the data stream has to be closed for data to be sent? Is there a way around this? Am I doing something wrong?

Sending multiple strings over same TCP connection in Java?

I have been trying for hours and I just can't seem to get it done. I want to send two strings from TCP client to server, and return them both capitalized. The two strings are username and password:
Client code is:
public void actionPerformed(ActionEvent e) {
final String s1 =textPane.getText(); //retrieve username
final String s2=passwordField.getText();//retrieve password
//**************************************************************************
//after we have gotten the credentials, we have to send them to the server to check in the database
Socket clientSocket = null; //create new socket
String response=null; //create what is supposed to become the server's response
String response2=null;
try {
/**
* construct the client socket, specify the IP address which is here
* localhost for the loopback device and the port number at which a
* connection needs to be initialized.
*/
clientSocket = new Socket("localhost", 6789);
// These streams are for the same purpose as in the server side //
DataOutputStream outToServer = new DataOutputStream(clientSocket
.getOutputStream());
DataOutputStream outToServer2 = new DataOutputStream(clientSocket
.getOutputStream());
BufferedReader inFromServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
// read the user's input from the console. //
// send the sentence to the server: note the need to append it with
// an endline character //
outToServer.writeBytes(s1 + '\n'); //send username
outToServer.writeBytes(s2 + '\n'); //send password
// listen on the socket and read the reply of the server //
response2=inFromServer.readLine();
response = inFromServer.readLine();
} catch (UnknownHostException ex) {// catch the exceptions //
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("FROM SERVER: " + response); //print the response of the server
System.out.println("FROM SERVER: " + response2);
try {
// close the socket when done //
clientSocket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
Bulk of Server Code is:
while(true) {
// connection socket //
Socket connectionSocket;
try {
// accept connection on the connection socket from the welcome socket which is a server socket //
connectionSocket = welcomeSocket.accept();
// Get the input stream from the connection socket and save it in a buffer //
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
// Allocate an output stream to send data back to the client //
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
// Read the client sentence from the receive buffer //
clientSentence = inFromClient.readLine();
clientSentence2=inFromClient.readLine();
System.out.println("From user: " + clientSentence);
// capitalize the client's sentence, here the server does actions on the client's data //
capitalizedSentence = clientSentence.toUpperCase() + '\n';
capitalizedSentence2=clientSentence2.toUpperCase()+'\n';
if(clientSentence.equalsIgnoreCase("QUIT")){// close the socket if the server sends a quit message //
connectionSocket.close();
System.out.println("Connection Socket Quitting");
// Note that here the server will not exit or end up it will just close the connection with the client //
}
else outToClient.writeBytes(capitalizedSentence);// Send the capitalized sentence back to the client //
} catch (IOException ex) {
ex.printStackTrace();
}
}
What am I doing wrong? Can't one buffered reader accept two separate strings? How do I separate them later?
You haven't written back capitalizedSentence2 back to client that's why client is waiting at second readLine() as mentioned below:
response2 = inFromServer.readLine();
response = inFromServer.readLine();
put below line in your server side code in else part
outToClient.writeBytes(capitalizedSentence2);
It might solve your problem.

Java Socket server side cannot read incoming line of text in play framework application

So I'm having some serious problems with Java's server side socket, which accepts connection, but it can't read anything from BufferedReader, which I have put to read the text stream from socket connection. Code for my threads run(), which I'm creating and running at the first time when any page is loaded.
public void run() {
try{
ServerSocket s = new ServerSocket(4100);
System.out.println("New tcp socket created");
Socket socket = s.accept();
System.out.println("New tcp update connection established.");
InputStream din = socket.getInputStream();
PrintWriter outp = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(din));
System.out.println("Streams created");
String inputline = "nothing yet...";
outp.println("hello from server");
while(true){
System.out.println("Got input from client:" + inputline);
inputline = in.readLine();
if(inputline == null || inputline.equals("exit")){
break;
}
}
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("Updater thread exits.");
}
This prints out everything properly, except for Got input from client: + what ever my client sends with PrintWriter which outputs to a socket.
Client side example:
Socket s = new Socket(serverip, serverDownloadsUpdatePort);
OutputStream dout = s.getOutputStream();
PrintWriter outp = new PrintWriter(dout);
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
System.out.println(in.readLine());//This prints out properly, what server sends to client
outp.println("test connection");
outp.println("Can you hear me?");
outp.println("exit");
s.close();
Your client may not be sending end-of-line characters along with its input, causing your server to wait indefinitely at "in.readLine()".
The Javadoc for BufferedReader's readLine method (http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html#readLine()) says: "Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed." Make sure that your client is sending input that conforms to this rule.
I was able to see client input using your server with the following client Runnable (but only if I include the "\n"):
public void run() {
try{
Socket writeSocket = new Socket("localhost", 4100);
PrintWriter out =
new PrintWriter(writeSocket.getOutputStream(), true);
out.write("Hello there!\n");
out.flush();
}
catch(Exception e){
e.printStackTrace();
}
}
EDIT: When using println as in the submitter's client example, you don't need to worry about adding "\n", but you do need to flush the socket. One way to make sure this happens is by setting autoFlush=true in the PrintWriter constructor.
I found out that I forgot to set PrintWriter as auto flushable at client side and thats why it didn't work becouse stream didn't got flushed at any time.

Send string to client upon command JAVA

So I am trying to have a sever sit and listen waiting for a connection from a client. The client sends over some string and the sever does some action based on whats received. Now what I would like to happen is the client sends over some command asking for data back and have the server get what it needs to and send the string back.
Not a big deal right? Well for some reason I can't get it working, my best guess is that its not closing the socket properly. I can't figure out why it wouldn't or what I am doing wrong.
Client
String data = "";
DataOutputStream outToServer = null;
BufferedReader input;
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes("GETDATA");
outToServer.flush();
input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
data = input.readLine();
Log.d("ANSWER: ", data);
input.close();
} catch (IOException e) {
Log.d("Error: ", e.toString());
}
Server
ServerSocket listeningSocket = new ServerSocket(9008);
BufferedReader fromClient ;
PrintStream os;
while(true) {
Socket clientSocket = listeningSocket.accept();
ServerConnection clientConnection = new ServerConnection(clientSocket);
os = new PrintStream(clientSocket.getOutputStream());
fromClient= new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
if(fromClient.readLine().equals("GETDATA")){
os.println("DATA");
os.flush();
clientSocket.wait();
clientSocket.close();
}
else{
clientConnection.run();
}
}
Any ideas?
here is your error
outToServer.writeBytes("GETDATA");
the right code is
outToServer.writeBytes("GETDATA\n");
as your using readline you should send a full line with line break

Categories