有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

通过Javasocket使用BufferedStream通过数据流发送文件

多个问题编辑之后没有回答(可能不会编辑那么多),我已经使用DataInput/OutputStreams实现了一个工作的服务器/客户机模型。我的最后一个问题是在哪里放置FileInputStream和FileOutputStream。到目前为止,我已经看到了带有输入的服务器示例和带有输出的其他示例。我现在唯一的问题是:

FileInputStream和FileOutputStream在哪里

传输服务器:

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);
        } 
    }
}

转让客户:

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.");
    }
}

编辑: 示例显示了具有输入流和输出流的服务器以及具有相同输入流和输出流的客户端的不同组合。 例1Java sending and receiving file (byte[]) over sockets

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

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


共 (0) 个答案