I am trying to write a program which uploads files from a client to a server. I think the issue I'm having at the moment is that the server doesn't wait for the client to start sending. Any pointers as to what is going wrong are greatly appreciated. The program has quite a lot in it including a GUI but I'll try and just include the relevant code.
Server
private InputStream in = null;
private OutputStream out = null;
private Socket socket;
private void startServer() {
try {
while (true) {
ServerSocket server = new ServerSocket(port);
System.out.println("Server started and listening on port " + port);
socket = server.accept();
System.out.println("Client connect from " + socket.getRemoteSocketAddress());
in = new FileInputStream("File10.txt");
out = socket.getOutputStream();
while (in.read() >= 0) {
receiveFile("File10.txt");
}
}
} catch (Exception e) {
System.out.println("File read failed");
}
}
private void receiveFile(String name) {
byte[] bytes = new byte[16 * 1024];
File file = new File(name);
int count = 0;
try {
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
System.out.println("File read");
}
} catch (Exception e) {
System.out.println("Could not read file");
}
}
Client
Queue<File> fileQueue = new ArrayDeque<File>();
private void startClient() {
try {
socket = new Socket(serverAddress, port);
System.out.println("Connected to server at " + socket.getRemoteSocketAddress());
} catch (Exception ex) {
System.out.println("Could not connect to server");
}
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Reader/writer started");
} catch (Exception e) {
System.out.println("Reader/writer failed to start");
}
}
private void sendFiles() {
byte[] bytes = new byte[(int) fileQueue.peek().length()];
int counter;
try {
fin = new FileInputStream(fileQueue.peek());
bin = new BufferedInputStream(fin);
} catch (Exception e) {
System.out.println("Could not start Reader");
}
try {
out = socket.getOutputStream();
out.write(bytes, 0, bytes.length);
System.out.println("Sending file ... ");
} catch (Exception e) {
System.out.println("Could not send file");
}
}
Ultimately the program will read files from a queue and upload them to the server. I'm only 8 weeks into learning Java and I might have been a bit ambitious with my choice of what to build.