【问题标题】:File Transfer in JavaJava中的文件传输
【发布时间】:2017-09-15 15:24:21
【问题描述】:

我正在尝试使用 java 中的套接字实现文件传输。我到目前为止,但问题是我无法将文件发送到服务器。客户端不写入文件的内容。我知道我需要创建一个循环,但我做不到。你能检查一下代码吗?我看不到问题。

客户端:

import java.io.*;
import java.net.*;
// Class Client Socket
public class ClientSocket
{
    public static void main(String[] args) throws IOException
    {
        // show main Menu
        System.out.println("Basic Client Socket Programming");
        // Socket Variables
        Socket clientSocket = null;             // for sending and receiving of data
        PrintWriter  outputStream = null;       // for sending data
        BufferedReader  inputStream = null;     // for receiving data
        BufferedInputStream bis;
        BufferedOutputStream bos;
        // Create and open socket
        // Connection to 127.0.0.1, port num=2001
        try
        {
            clientSocket = new Socket("127.0.0.1",  2001);
            outputStream = new PrintWriter(clientSocket.getOutputStream(), true);
            inputStream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        }
        catch (UnknownHostException e)
        {
            System.err.println("Don't know about host: 127.0.0.1");
            return;
        }
        catch (IOException e)
        {
            System.err.println("Couldn't get I/O for the connection to: 127.0.0.1");
            return;
        }
        // check if connection is successful
        if((clientSocket == null) || (outputStream == null) || (inputStream == null))
        {
            System.err.println("Socket Connection not successfull");
            return;
        }
        else
        {
            System.out.println("Socket Connected");
        }
        //generate MD5 and send data
        String hash = MD5.md5("Hello");
        System.out.println("Hash code generated: "+hash);
        //outputStream.println("Hello ||" + hash);
        //creates a new BufferWriter to write the hash value and the text message into the txt file.
        BufferedWriter out = new BufferedWriter(new FileWriter("hashedCode.txt"));
        out.write(hash); //writes the hash code to the file
        out.close(); //close the bufferreader
        //Send the file to the server
        bis = new BufferedInputStream(new FileInputStream("hashedCode.txt"));
        bos = new BufferedOutputStream(clientSocket.getOutputStream());
        byte[] byteArray = new byte[8192];
        int in;
        while ((in = bis.read(byteArray)) != -1)
        {
            bos.write(byteArray,0,in);
        }
        // receiving data
        String rcvData;
        rcvData = inputStream.readLine();
        System.out.println(rcvData);
        // close connections
        try
        {
            outputStream.close();
            inputStream.close();
            bis.close();
            bos.close();
            clientSocket.close();
            System.out.println("Connection closed.");
        }
        catch (UnknownHostException e)
        {
            System.err.println("Trying to connect to unknown host: " + e);
        }
        catch (IOException e)
        {
            System.err.println("IOException:  " + e);
        }
        // exit program
        return;
    }
}

服务器端

import java.io.*;
import java.net.*;
public class serverSocket
{
    public static void main(String[] args) throws IOException
    {
        // show main Menu
        System.out.println("Basic Client Socket Programming");
        // Socket Variables
        ServerSocket serverSocket = null;       // for listen for connection
        Socket  rcvSocket = null;               // for sending n rcving data
        DataOutputStream outputStream = null;   // for sending data
        DataInputStream inputStream = null;     // for receiving data
        BufferedInputStream bis;
        BufferedOutputStream bos;
        int inInt;
        byte[] data;
        // try to open a socket to listen for incoming data
        // port number must match the one that the client is connecting to
        try
        {
           serverSocket = new ServerSocket(2001);
        }
        catch (IOException e)
        {
           System.err.println(e);
        }
        // creating a socket to rcv incoming data
        while (true)
        {
            try
            {
                System.out.println("Listening");
                rcvSocket = serverSocket.accept();
                System.out.println("Connected");
                PrintWriter out = new PrintWriter(rcvSocket.getOutputStream(), true);
                BufferedReader in = new BufferedReader(new InputStreamReader(rcvSocket.getInputStream()));
                /*
                // initiate conversation with client
                String rcvData = in.readLine();
                System.out.println("Rcv Data: " + rcvData);
                */
            byte[] receivedData = new byte[8192];
            bis = new BufferedInputStream(rcvSocket.getInputStream());
            bos = new BufferedOutputStream(new FileOutputStream("receivedHashed.txt"));
            while ((inInt = bis.read(receivedData)) != -1)
            {
                bos.write(receivedData,0,inInt);
            }
            bos.flush();
                out.println("File received!");
            }
            catch (IOException e)
            {
               System.err.println(e);
            }
        }
    }
}

【问题讨论】:

  • 您已经创建了一个循环。这里没有UDP,只有TCP。不清楚你在问什么。

标签: java sockets tcp network-programming file-transfer


【解决方案1】:

您是否只需要从缓冲的输出流中刷新已写入的字节?

while ((in = bis.read(byteArray)) != -1)
{
    bos.write(byteArray,0,in);
}
bos.flush();

【讨论】:

  • 或者确实关闭它。
  • bos.close() 已经在下一个 try 块中调用,其中所有其他资源也已关闭。但是,如果 close() 隐式调用了 flush(),那么在这段代码 sn-p 中对 close() 的调用“为时已晚”,因为它也是在检查输入流的响应数据之后。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
相关资源
最近更新 更多