I am trying to send a file from client to server and then the server response the client. The server has received the file, but the client doesn't receive the response.
This is my Main and client code:
public static void main(String[] args) throws IOException {
startServer();
startSender();
}
public static void startSender() {
(new Thread() {
@Override
public void run() {
try {
Socket client = new Socket("localhost", 10000);
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
//sent a file
FileInputStream fis = new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\constructor.jpg"));
byte[] buffer = new byte[1024];
int length = 0;
while((length = fis.read(buffer, 0, buffer.length)) > 0){
oos.write(buffer, 0, length);
oos.flush();
}
//response
String response = (String) ois.readObject();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}).start();
}
Server:
public static void startServer() {
(new Thread() {
@Override
public void run() {
ServerSocket server = null;
Socket client = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
server = new ServerSocket(10000);
client = server.accept();
System.out.println("Connected!");
ois = new ObjectInputStream(client.getInputStream());
oos = new ObjectOutputStream(client.getOutputStream());
//receive the file
FileOutputStream fos = new FileOutputStream(new File("E:\\Java\\server\\constructor1.jpg"));
byte[] sendBytes = new byte[1024];
while(true) {
int read =0;
read = ois.read(sendBytes);
if(read == -1)
break;
fos.write(sendBytes, 0, read);
fos.flush();
}
//response
oos.writeObject("true");
oos.flush();
} catch (IOException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}).start();
}
What's wrong?