【问题标题】:java socket programming to send and receive file between two machinesjava socket编程在两台机器之间发送和接收文件
【发布时间】:2014-11-04 06:33:14
【问题描述】:

我正在尝试使用套接字编程在两台机器之间进行通信。

我基本上需要的是两台机器都应该能够发送和接收文件。我在下面粘贴的代码没有显示任何错误,但服务器端程序似乎无限期运行,即它没有终止。它卡在标有注释的行上。

在这段代码中,最初,服务器发送名为“file.txt”的文件,客户端接收并保存名为“copy.txt”的文件。稍后客户端正在发送一个名为“file2.txt”的文件,服务器正在接收并保存名为“copy2.txt”的文件。

有人可以告诉我错误并提出一些改进建议吗?

//server side code

import java.net.*; 
import java.io.*; 
public class server 
{ 
public static void main (String [] args ) throws IOException 
{ 

    //sending file started
    ServerSocket serverSocket = new ServerSocket(16167);
    Socket socket = serverSocket.accept(); 
    System.out.println("Accepted connection : " + socket); 
    File transferFile = new File ("/Users/abhishek/desktop/file.txt"); 
    byte [] bytearray = new byte [(int)transferFile.length()]; 
    FileInputStream fin = new FileInputStream(transferFile); 
    BufferedInputStream bin = new BufferedInputStream(fin); 
    bin.read(bytearray,0,bytearray.length); 
    OutputStream os = socket.getOutputStream(); 
    System.out.println("Sending Files..."); 
    os.write(bytearray,0,bytearray.length); 
    os.flush(); 
    System.out.println("File transfer complete"); 
    //socket.close();
    //sending comleted

    //receiving file started
    int filesize=1022386; 
    int bytesRead=0; 
    int currentTot = 0;  
    byte [] bytearray1 = new byte [filesize]; 

    InputStream is = socket.getInputStream(); 

    FileOutputStream fos = new FileOutputStream("/Users/abhishek/desktop/copy2.txt"); 
    //fos.flush(); 
    BufferedOutputStream bos = new BufferedOutputStream(fos); 
    //bos.flush(); 
    System.out.println("not moving ahead!!!");//program stucked here
    bytesRead = is.read(bytearray1,0,bytearray1.length); 
    currentTot = bytesRead; 
    System.out.println("current"+currentTot); 
    do 
    { 
        bytesRead = is.read(bytearray1, currentTot, (bytearray1.length-currentTot)); 
        if(bytesRead >= 0) 
            currentTot += bytesRead; 
        System.out.println("current"+currentTot); 
    } while(bytesRead > -1); 
    System.out.println("outside current"+currentTot);
    bos.write(bytearray1, 0 , currentTot); 
    bos.flush(); 
    //receiving complete
    System.out.println("Receving file completed"); 
    socket.close(); 

} 
}



//client side code
import java.net.*; 
import java.io.*; 


 public class client 
{ 
    public static void main (String [] args ) throws IOException 
    { 
        int filesize=1022386; 
        int bytesRead=0; 
        int currentTot = 0; 
        Socket socket = new Socket("localhost",16167); 
        byte [] bytearray = new byte [filesize]; 
        InputStream is = socket.getInputStream(); 
        FileOutputStream fos = new FileOutputStream("/Users/abhishek/desktop/copy.txt"); 
        BufferedOutputStream bos = new BufferedOutputStream(fos); 
        bytesRead = is.read(bytearray,0,bytearray.length); 
        currentTot = bytesRead; 
        do 
        { 
            bytesRead = is.read(bytearray, currentTot, (bytearray.length-currentTot)); 
            if(bytesRead >= 0) 
                currentTot += bytesRead; 
        } while(bytesRead > -1); 
        System.out.println("current"+currentTot);
        bos.write(bytearray, 0 , currentTot); 
        bos.flush(); 
        bos.close(); 
        System.out.println("receiving first file completed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

        //sending file
        System.out.println("sending second file started!");
        File transferFile = new File ("/Users/abhishek/desktop/file2.txt"); 
        byte [] bytearray2 = new byte [(int)transferFile.length()]; 
        FileInputStream fin = new FileInputStream(transferFile); 
        BufferedInputStream bin = new BufferedInputStream(fin); 
        bin.read(bytearray2,0,bytearray2.length); 
        OutputStream os = socket.getOutputStream();
        os.flush();
        os.write(bytearray2,0,bytearray2.length); 
        os.flush();
        System.out.println("sending second file completed!");
        //sending complete


        socket.close();
    } 
}

【问题讨论】:

    标签: java sockets


    【解决方案1】:

    System.out.println("not moving ahead!!!");//program stucked here 行真的执行了吗?如果是这样,那么问题在于 InputStream.read() 函数是阻塞函数;他们将停止执行程序(“块”),直到他们能够完成。

    来自JavaDoc for InputStream:

    从输入流中读取最多 len 个字节的数据到一个字节数组中。尝试读取多达 len 个字节,但可能会读取较小的字节数。实际读取的字节数以整数形式返回。 此方法会一直阻塞,直到输入数据可用、检测到文件结尾或引发异常。

    由于您没有遇到异常,这意味着当您调用 .read() 时,没有可读取的数据,并且您的程序等待读取数据(永远不会到达)。您应该首先检查您的客户端程序是否确实在发送数据。

    【讨论】:

    • 是的,该行正在执行,我确信它卡在 read() 上,因为没有可用的数据。但是,我正在从客户端发送数据(您可以检查客户端程序)。但是,我认为客户端没有完成读取第一个文件的数据(确实创建了一个名为“copy.txt”的文件,但其中没有数据)。因此,由于客户端没有完成第一个文件的读取部分,它无法为第二个文件发送数据。那么,我该如何避免这种情况呢?
    【解决方案2】:

    我敢打赌

    bytesRead = is.read(bytearray1,0,bytearray1.length);

    是你真正陷入困境的地方。如果你卡在这里,通常的问题是通信的另一端没有发送任何数据,没有什么可读取的,你的线程卡在等待它发送。

    在您的客户端,您调用

    bos.close();

    在发送第一条消息之后。这也将导致套接字关闭,这将在您的服务器端抛出一个 IOException,并且由于您没有捕获 IOException,您的服务器程序将退出。

    你有多少插座经验?如果您刚开始使用套接字,您可能想查看我围绕此编写的扩展,从 ServerSocketEx 和 DataFetcher 开始。

    【讨论】:

    • 这感觉应该放在评论里。
    • @StackOverflowException 我已更新此内容以回答所提出的问题,并包含此建议。
    • 是的,这就是我卡住的地方。我是第一次进行套接字编程,所以请您告诉我可以避免这种情况的任何方法。另外,请阅读我对下面@Nekojimi 回复的评论,以便更好地了解我的问题。
    • @StackOverflowException 刚刚更新了我的答案。您的问题出在客户端调用 bos.close()
    • @user3245573:他的意思是你。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    • 1970-01-01
    • 2010-10-15
    相关资源
    最近更新 更多