DataOutPutStream:获取套接字写入错误

时间:2013-04-02 23:01:29

标签: java sockets dataoutputstream

我正在用Java编写P2P网络,其中每个节点都相互发送文件。

目前我的代码显示一个奇怪的错误,我无法弄清楚原因。以下是错误:

  

java.net.SocketException:软件导致连接中止:套接字   写错误

这是我发送文件的代码:

 public void sendRequest(String fileName, String host, int port ) throws UnknownHostException, IOException
        {
            Socket socket = new Socket("localhost", port);
            OutputStream os = socket.getOutputStream();
            DataOutputStream dos = new DataOutputStream(os);
            File myFile = new File(fileName);
            byte[] mybytearray = new byte[(int) myFile.length()];  


            dos.writeUTF( myFile.getName());  //send file name
            dos.writeLong(mybytearray.length);  //send file size
            System.out.println("file size: "+mybytearray.length);
            dos.write(mybytearray, 0, mybytearray.length);  //send file content
            dos.flush(); 
            dos.close();
            socket.close();
    }

以下代码收到文件:

private void processRequest( )
    {
        int bytesRead; 
        OutputStream output  = null;

        try
        {
            InputStream in = socket.getInputStream();  
            DataInputStream clientData = new DataInputStream(in);  
            String fileName = clientData.readUTF();

            //System.out.println(this.currentNodeName +"Has received file: "+fileName);

            //if file already exists, then just send friends
            File file = new File(this.dirLocation+fileName);

            if( !file.exists() )
            {

                output = new FileOutputStream(this.dirLocation+fileName); //get file name
                long size = clientData.readLong();//get file size
                byte[] buffer = new byte[1024]; 

                //read file content and save the file
                //System.out.println(this.currentNodeName +"saves the file");
                while (size > 0 && ( bytesRead = clientData.read(buffer, 0, (int)Math.min(buffer.length, size))) != -1 )     
                {     
                    output.write(buffer, 0, bytesRead);     
                    size -= bytesRead;     
                } 
                output.close();

}

我做错了什么?

我正在使用DataOutputStream,因为我需要将文件名和文件大小发送到接收节点。

0 个答案:

没有答案