文件传输 - Java套接字编程

时间:2014-01-06 09:49:10

标签: java file sockets

我有以下服务器和客户端代码。客户轮胎将文件称为“testprgm.txt”,大小为2000B,表示服务器,将其保存为“Test.txt”。问题是我可以看到服务器和客户端上的字节传输,但是当我在运行这些代码后看到Test.txt文件的大小时,它就是ZERO。

服务器程序:

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

2 个答案:

答案 0 :(得分:1)

我会使用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);
    }

答案 1 :(得分:0)

您的服务器副本循环是正确的,因为它使用read()方法调用中write()返回的计数。您的客户端副本循环应该这样做。它没有。

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

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