Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.vungueanu;
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.PrintWriter;
- import java.net.Socket;
- public class doComms implements Runnable {
- private File directory = null;
- private Socket connection = null;
- private BufferedReader incoming = null;
- private PrintWriter outgoing = null;
- /**
- * Makes conn and starts the thread
- * @param directory
- * @param connection
- */
- doComms (File directory, Socket connection) {
- this.directory = directory;
- this.connection = connection;
- System.out.println("New connection!\n");
- (new Thread(this)).start();
- }
- /**
- * Sends the names of the files over the connection
- */
- private void index () {
- String[] fileList = directory.list();
- for (int i = 0; i < fileList.length; ++i)
- outgoing.println(fileList[i]);
- outgoing.flush();
- outgoing.close();
- }
- /**
- * Sends the file requested
- * @param fileName the file
- * @throws IOException
- */
- private void send (String fileName) throws IOException {
- File file = new File(directory, fileName);
- if (!file.exists() || file.isDirectory()) {
- outgoing.println("Error with the file!");
- }
- else {
- //outgoing.println("OK!");
- BufferedReader in = new BufferedReader (new FileReader (file));
- String line = "";
- while ((line = in.readLine()) != null) {
- outgoing.println(line);
- }
- outgoing.flush();
- outgoing.close();
- in.close();
- }
- }
- @Override
- public void run() {
- String command = "";
- try {
- incoming = new BufferedReader (new InputStreamReader (connection.getInputStream()));
- outgoing = new PrintWriter (connection.getOutputStream() );
- command = incoming.readLine();
- if (command.equals("index")) {
- this.index();
- return;
- }
- else if (command.startsWith("get")) {
- String fileName = command.substring(3).trim();
- this.send (fileName);
- }
- else {
- outgoing.println("Unknown command\n");
- outgoing.flush();
- }
- } catch (IOException e) {
- System.out.println("Error with command " + command + "\n");
- } finally {
- try {
- connection.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment