Java Socket reading response from other application
Java Socket reading response from other application
I'm currently making a connection from a software to an application using java socket.
The code is more or less like this
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Input {
public static void main(String args) {
try{
Socket s=new Socket("ok",10003);
PrintWriter printWriter = new PrintWriter(s.getOutputStream());
Scanner scanner = new Scanner( System.in );
BufferedReader inserver = new BufferedReader(new
InputStreamReader(s.getInputStream()));
String str = scanner.nextLine();
String hisscanner = "u0002"+str+"u0003";
printWriter.write(hisscanner);
s.shutdownInput();
String response = inserver.readLine();
System.out.println("FROM SERVER: " + response);
printWriter.close();
s.close();
scanner.close();
}catch (UnknownHostException ex) {
System.out.println("Could not connect to the server [Unknown exception]");
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}}
So we send a string to the application, and the application should reply back a string. It has successfully sent the string to the application, and that application is also showing a reply correctly.
Example of the application log:
https://ibb.co/ikLxNJ
The problem is, the reply won't show up in the console of software I made.
The console :
https://ibb.co/e5fghJ
The software I run always returns with NULL, can someone help point out whats wrong and help me corrects it?
s.shutdownInput();
i changed to s.shutdownOutput(); and it wont send the string to the application. if i deleted it, the software doesn't show anything and won't stop running
– M.Fauzan
2 days ago
You'd probably need a
printWriter.flush()
call before you run shutdownOutput, but before you run printWriter.write(hisscanner);
– nos
2 days ago
printWriter.flush()
printWriter.write(hisscanner);
all right, i wrote it like this printWriter.flush(); s.shutdownOutput(); printWriter.write(hisscanner); it still doesn't send the string to the application
– M.Fauzan
2 days ago
Well, now you are flushing before you write anything , and you are even shutting down the output before you write anything - how can that work ? printWriter.write(hisscanner); printWriter.flush(); s.shutdownOutput(); seems like the proper sequence.
– nos
2 days ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Surely you should not run
s.shutdownInput();
to close the input before you try to read from the socket ?– nos
Jun 29 at 9:10