I used a socket in my client class and try to get a string from server that is written into DataOutputStream successfully. Below is the sample code.
try(Socket socket = new Socket(ip, port);)
{
// Output and Input Stream
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
//receive message from server
while(true && input.available() > 0)
{
String message = input.readUTF();
System.out.println(message);
TextArea.setText(message);
}
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
However, when my client wants to show that message in a TextArea. It appears that input.available()=0 so it doesn't show that message. But when I print out the message string, it's really confusing that it is the exact string I want. Finally I just get rid of the while-statement and directly use TextArea.setText(message) to show that message.
Anyone can help me clarify that?
What protocol is the server expecting? If the server is expecting some request first (e.g. HTTP), you'll need to send a request before expecting any bytes sent in the input stream (a reason that input.available is 0).
See here for an example: https://www.infoworld.com/article/2853780/socket-programming-for-scalable-systems.html