I use following code to send and receive JSON data to and from a PHP Swoole Server.
I see the response from the server coming in (on Wireshark) but not interpreted by the Java TCP Client.
Does anyone know how to read incoming JSON data properly?
Here is the code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class TcpClient {
public static void main(String[] args) {
String serverAddress = "192.168.15.200"; // Replace with the server IP address
int serverPort = 9000; // Replace with the server port
try {
// Create a socket and connect to the server
Socket socket = new Socket(serverAddress, serverPort);
// Get the input and output streams
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
// Send a message to the server
String rootDir = ".";
String JSON_DATA = "{\"messagetype\":\"DirectoryInfoRequest\",\"curre ntdir\":\"" + rootDir + "\"}";
// String message = JSON_DATA;
writer.println(JSON_DATA);
// Receive the response from the server
String line;
StringBuilder responseBuilder = new StringBuilder();
>>>>> while ((line = reader.readLine()) != null) { <<<<< hanging!
responseBuilder.append(line);
}
System.out.println("Response from server: " + responseBuilder.toString());
// Close the streams and socket
reader.close();
writer.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The application is hanging on the readLine() command.
Thanks.