java socket编程在两台机器之间发送和接收文件

时间:2014-09-10 14:39:17

标签: java sockets

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

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

在此代码中,服务器最初发送名为“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();
    } 
}

2 个答案:

答案 0 :(得分:0)

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

来自JavaDoc for InputStream

  

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

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

答案 1 :(得分:-1)

我打赌

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

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

在您的客户端,您致电

bos.close();

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

你有多少套接字体验?如果您刚刚开始使用套接字,那么您可能需要查看我在此处撰写的扩展程序,从ServerSocketExDataFetcher开始。