【问题标题】:Java Socket MultiThread File TransferJava Socket 多线程文件传输
【发布时间】:2014-09-10 18:35:13
【问题描述】:

我的代码有问题。 我不知道如何解决。 我需要发送一个文件,然后下载相同的文件。 发生的情况是我可以发送多个文件,但如果我只下载一个,我将无法发送任何内容。因为套接字是关闭的。 我绞尽脑汁也解决不了。 有没有人有任何提示? 谢谢。

服务器.java

public class Server {

    private static ServerSocket serverSocket;
    private static Socket clientSocket = null;

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

        try {
            serverSocket = new ServerSocket(4444);
            System.out.println("Server started.");
        } catch (Exception e) {
            System.err.println("Port in use.");
            System.exit(1);
        }

        while (true) {
            try {
                clientSocket = serverSocket.accept();
                System.out.println("Conection Accept : " + clientSocket);

                Thread t = new Thread(new ClientConnection(clientSocket));

                t.start();

            } catch (Exception e) {
                System.err.println("Conection Error.");
            }
        }
    }
}

ClientConnection.java

public class ClientConnection implements Runnable {

    private Socket clientSocket;
    private BufferedReader in = null;

    public ClientConnection(Socket client) {
        this.clientSocket = client;
    }

    @Override
    public void run() {
        boolean done = false;
        try{
            in = new BufferedReader(new InputStreamReader(
                    clientSocket.getInputStream()));

        }
        catch(Exception e){}

        String clientSelection;

        while (!done) {

            try {


                clientSelection = "";

                while ((clientSelection = in.readLine()) != null) {
                    switch (clientSelection) {
                    case "send":
                        receiveFile();
                        break;
                    case "get":
                        String outGoingFileName;
                        while ((outGoingFileName = in.readLine()) != null) {
                            sendFile(outGoingFileName);
                        }
                        break;
                    default:
                        System.out.println("Wrong Command...");
                        break;
                    }
                }

            } catch (IOException ex) {
                System.err.println("Erro--" + ex);
            }
        }
    }

    public void receiveFile() {
        try {
            int bytesRead;

            DataInputStream clientData = new DataInputStream(
                    clientSocket.getInputStream());

            String fileName = clientData.readUTF();
            OutputStream output = new FileOutputStream(
                    ("received_from_client_" + fileName));
            long size = clientData.readLong();
            byte[] buffer = new byte[1024];
            while (size > 0
                    && (bytesRead = clientData.read(buffer, 0,
                            (int) Math.min(buffer.length, size))) != -1) {
                output.write(buffer, 0, bytesRead);
                size -= bytesRead;
            }
            output.flush();
            output.close();

            System.out.println("File " + fileName + " received from client.");

        } catch (IOException ex) {
            System.err.println("Error." + ex);
        }
    }

    public void sendFile(String fileName) {
        try {

            File myFile = new File(fileName);
            byte[] mybytearray = new byte[(int) myFile.length()];

            FileInputStream fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);

            DataInputStream dis = new DataInputStream(bis);
            dis.readFully(mybytearray, 0, mybytearray.length);

            OutputStream os = clientSocket.getOutputStream();

            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(myFile.getName());
            dos.writeLong(mybytearray.length);
            dos.write(mybytearray, 0, mybytearray.length);
            dos.flush();

            System.out.println("File " + fileName + " send to client.");

        } catch (Exception e) {
            System.err.println("Error! " + e);
        }
    }
}

Client.java

public class Client {

    private static Socket sock;
    private static String fileName;
    private static String newName;
    private static BufferedReader bufferReader;
    private static PrintStream os;


    public static void main(String[] args) throws IOException {
        try {
            sock = new Socket("localhost", 4444);
            bufferReader = new BufferedReader(new InputStreamReader(System.in));
        } catch (Exception e) {
            System.err.println("Error - Try again.");
            System.exit(1);
        }

        os = new PrintStream(sock.getOutputStream());

        boolean done = false;

        while (!done) {
            try {

                switch (selectAction()) {
                case "send":
                    os.println("send");
                    sendFile();
                    break;
                case "get":
                    os.println("get");
                    System.err.print("File Name: ");
                    fileName = bufferReader.readLine();
                    os.println(fileName);
                    receiveFile(fileName);
                    break;
                case "exit":
                    done = true;
                    os.println("exit");
                    System.out.println("Connection closed");
                    break;
                }
            } catch (Exception e) {
                System.err.println("Wrong command");
            }
        }

        sock.close();
    }

    public static String selectAction() throws IOException {
        System.out.println("");
        System.out.println("send - Send File.");
        System.out.println("get - Get File.");
        System.out.println("exit - Exit.");
        System.out.print("\nSelect one Option: ");

        return bufferReader.readLine();
    }

    public static void sendFile() {
        try {
            System.err.print("File Name: ");
            fileName = bufferReader.readLine();

            File myFile = new File(fileName);
            byte[] mybytearray = new byte[(int) myFile.length()];

            FileInputStream fis = new FileInputStream(myFile);
            BufferedInputStream bis = new BufferedInputStream(fis);

            DataInputStream dis = new DataInputStream(bis);
            dis.readFully(mybytearray, 0, mybytearray.length);

            OutputStream os = sock.getOutputStream();

            DataOutputStream dos = new DataOutputStream(os);
            dos.writeUTF(myFile.getName());
            dos.writeLong(mybytearray.length);
            dos.write(mybytearray, 0, mybytearray.length);
            dos.flush();


            System.out.println("File " + fileName
                    + " send to server.");
        } catch (Exception e) {
            System.err.println("ERROR! " + e);
        }
    }

    public static void receiveFile(String fileName) {
        try {
            int bytesRead;
            InputStream in = sock.getInputStream();

            DataInputStream clientData = new DataInputStream(in);

            fileName = clientData.readUTF();
            OutputStream output = new FileOutputStream(
                    ("received_from_server_" + fileName));
            long size = clientData.readLong();
            byte[] buffer = new byte[1024];
            while (size > 0
                    && (bytesRead = clientData.read(buffer, 0,
                            (int) Math.min(buffer.length, size))) != -1) {
                output.write(buffer, 0, bytesRead);
                size -= bytesRead;
            }
            output.flush();

            System.out
                    .println("File " + fileName + " received from Server.");
        } catch (IOException ex) {
            Logger.getLogger(ClientConnection.class.getName()).log(Level.SEVERE,
                    null, ex);
        }
    }
}

谢谢。

【问题讨论】:

  • 您遇到的异常究竟是什么?堆栈跟踪在哪里?
  • @kolossus 在调试中显示以下内容.. java.net.SocketException: Connection reset by peer: socket write error...

标签: java multithreading sockets jakarta-ee console


【解决方案1】:

经过多次修改。我找到了解决方法。

一个“虽然”最终污染了一个变量。 至少这是我确定的。

在我的情况下(ClientConnection.java)

case "get":
        String outGoingFileName;
        while ((outGoingFileName = in.readLine()) != null) {
            sendFile(outGoingFileName);
        }
break;

解决了这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2011-10-05
    相关资源
    最近更新 更多