I'm trying to make a simple server/client application sending messages and files.
My client first sends the file's name, then the file itself and finally waits for server's response.
My server does the opposit, read file's name, read file, send response.
The issue is that the client is stuck at String response = dataInputStream.readUTF();
while the server is stuck at Files.copy(Paths.get(fileName), dataOutputStream);
I tried to remove String response = dataInputStream.readUTF();
from client and it works fine without it. Can someone help me understand why it's stuck when I do the readUtf()
after sending file ?
Thank you
Here's my Client
public static void main(String[] args) throws IOException {
String fileName = "hello.txt";
try (Socket clientSocket = new Socket(HOST, PORT)) {
DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
dataOutputStream.writeUTF(fileName);
Files.copy(Paths.get(fileName), dataOutputStream);
String response = dataInputStream.readUTF();
LOGGER.info(response);
}
}
And here's my Server
public static void main(String args[]) throws IOException {
try (ServerSocket ss = new ServerSocket(PORT)) {
Socket clientSocket = ss.accept();
DataOutputStream dataOutputStream = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream dataInputStream = new DataInputStream(clientSocket.getInputStream());
String fileName = dataInputStream.readUTF();
Files.copy(dataInputStream, Paths.get(fileName));
dataOutputStream.writeUTF("New file saved");
}
}