文件传输 - Java 套接字编程



我有以下服务器和客户端代码。客户端尝试将大小为2000B的文件"testprgm.txt"传输到服务器,并将其保存为"Test.txt"。问题是我可以看到服务器和客户端上的字节传输,但是当我在运行这些代码后看到 Test.txt 文件的大小时,它是零。

服务器程序:

import java.io.*;
import java.net.*;
public class ServerTest {
    public static void main(String[] args) {
        System.out.println("**********Server Program**************");
        int byteRead = 0;
        try {
            ServerSocket serverSocket = new ServerSocket(9999);
            if (!serverSocket.isBound())
                System.out.println("Sever Socket not Bounded...");
            else
                System.out.println("Server Socket bounded to Port : " + serverSocket.getLocalPort());
            Socket clientSocket = serverSocket.accept();
            if (!clientSocket.isConnected())
                System.out.println("Client Socket not Connected...");
            else
                System.out.println("Client Socket Connected : " + clientSocket.getInetAddress());
            while (true) {
                InputStream in = clientSocket.getInputStream();
                OutputStream os = new FileOutputStream("<DESTINATION PATH>/Test.txt");
                byte[] byteArray = new byte[100];
                while ((byteRead = in .read(byteArray, 0, byteArray.length)) != -1) {
                    os.write(byteArray, 0, byteRead);
                    System.out.println("No. of Bytes Received : " + byteRead);
                }
                synchronized(os) {
                    os.wait(100);
                }
                os.close();
                serverSocket.close();
                //System.out.println("File Received...");
            }
        } catch (Exception e) {
            System.out.println("Server Exception : " + e.getMessage());
            e.printStackTrace();
        }
    }
}

客户计划 :

import java.io.*;
import java.net.*;
public class Clientprgm {
public static void main(String[] args)
{
    Socket socket;
    try
    {
        socket = new Socket("SERVER IP ADDRESS>", 9999);            
        if(!socket.isConnected())
            System.out.println("Socket Connection Not established");
        else
            System.out.println("Socket Connection established : "+socket.getInetAddress());
        File myfile = new File("<SOURCE PATH>/testprgm.txt");       //local file path.

        if(!myfile.exists())
            System.out.println("File Not Existing.");
        else
            System.out.println("File Existing.");
        byte[] byteArray = new byte[1024];
        FileInputStream fis = new FileInputStream(myfile);
        BufferedInputStream bis = new BufferedInputStream(fis);
        OutputStream os = socket.getOutputStream();
        int trxBytes =0;
        while((trxBytes = bis.read(byteArray, 0, byteArray.length)) !=-1)
        {           
        os.write(byteArray, 0, byteArray.length);
        System.out.println("Transfering bytes : "+trxBytes );
        }
        os.flush();
        bis.close();
        socket.close();
        System.out.println("File Transfered...");
    }
    catch(Exception e)
    {
        System.out.println("Client Exception : "+e.getMessage());
    }       
}
}

我会使用 NIO 进行文件传输,它更短、更高效。这是客户端:

    try (SocketChannel sc = SocketChannel.open(new InetSocketAddress(
            hostaddress, 9999));
            FileChannel fc = new FileInputStream("test").getChannel()) {
        fc.transferTo(0, fc.size(), sc);
    }
    System.out.println("File Transfered...");

服务器端:

    ServerSocketChannel ss = ServerSocketChannel.open();
    ss.bind(new InetSocketAddress("localhost", 9999));
    try (SocketChannel sc = ss.accept();
            FileChannel fc = new FileOutputStream("test").getChannel()) {
        fc.transferFrom(sc, 0, Long.MAX_VALUE);
    }

服务器复制循环是正确的,因为它使用 read()write() 方法调用中返回的计数。客户端复制循环也应执行相同的操作。其实不然。

在任何情况下,您的协议都是基于谬误的。 套接字输入流上的read()将在对等方关闭连接时返回 -1,而不是之前。因此,将一个当read()返回 -1 时终止的循环放入另一个使用相同连接的循环中是不可能的。您似乎正在尝试通过单个连接发送多个文件。您需要在每个文件之前发送长度,并且每个文件只读取那么多字节。

否则,您需要在发送单个文件后关闭连接,并删除接收器中的外部循环。

最新更新