0

Multiple question edits with no responses later (should probably not edit that much), and I have arrived with a working server/client model using DataInput/OutputStreams. My last issue is where to place the FileInputStream and FileOutputStream. So far I have seen what appears to be server examples with the Input and others with the Output. My only question now is:

Where does the FileInputStream and FileOutputStream go?

TransferServer:

import java.net.*; 
import java.io.*; 
public class TransferServer extends Thread {    

    //protected values for use only within the TransferServer
    //serverContinue to keep the "server" running
    //and a new Socket for each client that connects to the "server"
    protected static boolean serverContinue = true;
    protected Socket clientSocket;

    public static void main(String[] args) throws IOException{ 

        //initialize a ServerSocket variable
        ServerSocket serverSocket = null; 

        //try to open a new ServerSocket in port 386
        try { 
            serverSocket = new ServerSocket(386); 
            System.out.println ("Connection Socket Created");
            try { 
                //while the server has not been told to close
                //wait for a new client connection
                while (serverContinue){
                    System.out.println ("Waiting for Connection");
                    new TransferServer (serverSocket.accept()); 
                }
            } 
            //if a new client connection wasn't possible print the error
            catch (IOException e){ 
                System.err.println("Accept failed."); 
                System.exit(1); 
            } 
        } 
        //failed to open on port 386
        catch (IOException e){ 
            System.err.println("Could not listen on port: 386."); 
            System.exit(1); 
        } 
        finally{
            //when the server is shutting down close the ServerSocket in port 386
            try {
                serverSocket.close(); 
            }
            //if closing the socket fails, display an error
            catch (IOException e){ 
                System.err.println("Could not close port: 386."); 
                System.exit(1); 
             } 
        }
    }
    //constructor creates a new socket and starts it
    private TransferServer(Socket clientSoc){
        clientSocket = clientSoc;
        start();
    }

    //overridden Thread run method
    public void run(){

        System.out.println("New Communication Thread Started");

        //open new read, write instances and echo the message back to the client
        try { 

            //open Buffered Data Streams for receiving and writing to client
            //data streams for translating bytes directly
            DataInputStream dis = 
                    new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
            DataOutputStream dos = 
                    new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
            //string to hold client input
            String inputLine; 

            //communications loop
            while (serverContinue){
                //read in user command and report it to the console
                inputLine = dis.readUTF();
                System.out.println("Server: " + inputLine); 

                //special case user inputs
                //end thread communications loop
                if (inputLine.equals("Bye.")) 
                    break; 
                //end server command
                if (inputLine.equals("End Server.")) 
                    serverContinue = false;
                //transfer file command
                if(inputLine.equals("file")){
                    System.out.println("Starting file transfer session.");
                    //create contents needed for file transfer;
                    String fileName, fileDest;
                    //File myFile = null;
                    //FileInputStream fis = null;
                    //byte[] mybytearray;


                    //read in file name, prep for transfer and report to server
                    fileName = dis.readUTF();
                    //myFile = new File( fileName );
                    //mybytearray = new byte[(int) myFile.length()];
                    System.out.println("Origin file: " + fileName);

                    /*open the input file stream for transfer
                    try {
                        fis = new FileInputStream(myFile);
                        dis = new BufferedInputStream(fis);
                    } catch (FileNotFoundException ex) {
                        System.out.println("Could not open fileInputStream in server");
                    }*/

                    dos.writeUTF("Starting file transfer with: " + fileName);
                    dos.flush();
                    //read in destination file name, report to server
                    fileDest = dis.readUTF();
                    System.out.println("File destination: " + fileDest);
                    dos.writeUTF(fileName + " will be sent to " + fileDest);
                    dos.flush();
                    /*is = new BufferedInputStream(fis);
                    try {
                        dis.read(mybytearray, 0, mybytearray.length);
                        dos.write(mybytearray, 0, mybytearray.length);
                        dos.flush();
                        dos.close();
                    } catch (IOException ex) {
                        System.out.println("Problem writing file out to client.");
                    }*/
                    dos.writeUTF("File " + fileName + " sent to " + fileDest);
                    dos.flush();
                }

                //write to the output stream
                dos.writeUTF(inputLine);
                dos.flush();
            } 
            //user leaving server, close all sockets
            dos.close(); 
            dis.close(); 
            clientSocket.close(); 
        } 
        //if there was any issue with communication print it
        catch (IOException e){ 
            System.err.println("Problem connecting to client socket.");
            System.exit(1);
        } 
    }
}

TransferClient:

import java.io.*;
import java.net.*;

public class TransferClient {
    public static void main(String[] args) throws IOException {

        //default server host is the local host
        String serverHostname = new String ("127.0.0.1");

        //if a host argument has been passed to the program, use that
        //host instead
        if (args.length > 0)
           serverHostname = args[0];
        System.out.println("Attemping to connect to host " + serverHostname + " on port 386.");

        //initialize the default Socket, PrintWriter and BufferedReader variables
        Socket clientSocket = null;
        DataOutputStream out = null;
        DataInputStream in = null;

        try {
            //open a new socket connection to the local host at port 386
            clientSocket = new Socket(serverHostname, 386);
            try {
                //open new input and output streams to communicate with "server" data streams to translate data directly
                out = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream()));
                in = new DataInputStream(new BufferedInputStream(clientSocket.getInputStream()));
            }
            catch(IOException e){
                System.out.println("Unable to open data streams.");
            }
        }
        //if the local host cannot be found
        catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + serverHostname);
            System.exit(1);
        }
        //if any error occurs opening the socket or one of the input/output streams
        catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: " + serverHostname);
            System.exit(1);
        }

        //buffered reader to read in console commands
        BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
        String userInput;

        //directions to terminate server communications loop
        System.out.println("Available commands:");
        System.out.println("\"Bye.\" to quit.");
        System.out.println("\"End Server.\" to shut down the localhost.");
        System.out.println("\"file\" to start a file transfer.");
        System.out.print("Command: ");
        //server communication loop reads in user input  
        while ((userInput = stdIn.readLine()) != null){

            //prints the user command to the server
            out.writeUTF(userInput);
            out.flush();

            //end loop at users request
            if (userInput.equals("Bye.")){
                System.out.println ("Session quit requested...");
                break;
            }
            //start a file transfer
            if(userInput.equals("file")){
                //Strings to hold file names
                String file_to_send = null;
                String file_to_receive = null;

                //byte array for file transfer
                //FileOutputStream fos = null;
                //byte[] aByte = new byte[1];
                //int bytesRead = 0;
                //ByteArrayOutputStream baos = new ByteArrayOutputStream();

                //pass command to server
                //out.writeUTF(userInput);

                //get file_to_send information, report it to server
                System.out.print("File to be sent: ");
                file_to_send = stdIn.readLine();
                out.writeUTF(file_to_send);
                out.flush();

                //fis = new FileInputStream(file_to_send);
                System.out.println("Server says: \"" + in.readUTF() +"\"");

                /*get file_to_receive information and open fileOutputStream
                try{
                    */System.out.print("New file location: ");
                    file_to_receive = stdIn.readLine();
                    out.writeUTF(file_to_receive);
                    out.flush();
                    //fos = new FileOutputStream(file_to_receive);
                    //baos = new ByteArrayOutputStream();
                    System.out.println("Server says: \"" + in.readUTF() +"\"");
                /*}
                catch(IOException ex){
                    System.out.println("Unable to open outputfilestream to: " + file_to_receive);
                }

                try{
                    InputStream is = clientSocket.getInputStream();
                    bos = new BufferedOutputStream(fos);
                    bytesRead = is.read(aByte, 0, aByte.length);

                    do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                    } while (bytesRead != -1);

                    bos.write(baos.toByteArray());
                    bos.flush();
                    bos.close();
                } catch (IOException ex) {
                    // Do exception handling
                }*/
            }
            //ready for next input
            System.out.println("echo: " + in.readUTF());
            System.out.print("Next command: ");
        }
        //close all open streams and the client socket
        out.close();
        in.close();
        stdIn.close();
        clientSocket.close();
        System.out.println ("Request successfully terminated.");
    }
}

EDIT: Examples showing different combinations of servers with input streams and outputstreams and clients with the same. Ex1. Java sending and receiving file (byte[]) over sockets

Ex2. http://www.rgagnon.com/javadetails/java-0542.html

Ex3. http://www.java2s.com/Code/Java/Network-Protocol/TransferafileviaSocket.htm

Jesus Garcia
  • 11
  • 1
  • 3
  • *"Where does the FileInputStream and FileOutputStream go?"* — What exactly is the problem you are facing? Doesn't the code do what it's supposed to do? If not, then what's the actual output? – MC Emperor Oct 10 '17 at 07:00
  • The problem was that I didn't know which end was supposed to read in the file and which end was supposed to read out the file so at this point, nothing. All this code does is tells whoever is monitoring the server and the user requesting a transfer what files are to be transferred and where. It took a while and given the difficulty figuring it out (specifically using DataStream wrapped BufferedStreams), I'll be uploading the fully functioning version of the program later after I've cleaned it up some. – Jesus Garcia Oct 10 '17 at 16:40

0 Answers0