2013-04-16 175 views
0

我有一个服务器和客户端连接使用套接字来传输文件,但如果我想能够从客户端发送字符串到用户JButton操作时服务器,它会抛出套接字关闭错误(因为我用dos发件人()构造函数中的.close())。问题是,如果我不使用dos.close(),客户端程序将不会运行/ init UI框架。我究竟做错了什么?我需要能够在程序第一次运行时发送文件,然后再发送数据。套接字关闭问题

发件人:

public Sender(Socket socket) { 

    List<File> files = new ArrayList<File>(); 
    files.add(new File(Directory.getDataPath("default.docx"))); 
    files.add(new File(Directory.getDataPath("database.db"))); 

    try { 
     BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream()); 
     DataOutputStream dos = new DataOutputStream(bos); 
     dos.writeInt(files.size()); 
     for (File file : files) { 
      dos.writeLong(file.length()); 
      dos.writeUTF(file.getName()); 
      FileInputStream fis = new FileInputStream(file); 
      BufferedInputStream bis = new BufferedInputStream(fis); 
      int theByte = 0; 
      while ((theByte = bis.read()) != -1) { 
       bos.write(theByte); 
      } 
      bis.close(); 
     } 
     dos.close(); // If this is disabled, the program won't work. 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

下载:

public static byte[] document; 

public Downloader(Socket socket) { 
    try { 
     BufferedInputStream bis = new BufferedInputStream(socket.getInputStream()); 
     DataInputStream dis = new DataInputStream(bis); 
     int filesCount = dis.readInt(); 
     for (int i = 0; i < filesCount; i++) { 
      long size = dis.readLong(); 
      String fileName = dis.readUTF(); 
      if (fileName.equals("database.db")) { 
       List<String> data = new ArrayList<String>(); 
       BufferedReader reader = new BufferedReader(new InputStreamReader(bis)); 
       String line; 
       while ((line = reader.readLine()) != null) { 
        if (line.trim().length() > 0) { 
         data.add(line); 
        } 
       } 
       reader.close(); 
       parse(data); 
      } else if (fileName.equals("default.docx")) { 
       ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
       for (int x = 0; x < size; x++) { 
        bos.write(bis.read()); 
       } 
       bos.close(); 
       document = bos.toByteArray(); 
      } 
     } 
     //dis.close(); 
     } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

回答

0

在客户端你的第一个接收循环终止在EOS,仅当您在发送关闭套接字发生,你不想做。你要发送的长度提前在每种情况下的文件,以便接收代码看起来应该像这样在两种情况下:

long total = 0; 
while ((total < size && (count = in.read(buffer, 0, size-total > buffer.length ? buffer.length : (int)(size-total))) > 0) 
{ 
    total += count; 
    out.write(buffer, 0, count); 
} 
out.close(); 

这个循环从套接字读取输入流中恰好size字节,并将其写入到OutputStreamout ,无论out恰巧是:在第一种情况下,一个FileOutputStream,在第二个,ByteArrayOutputStream

+0

所以我会用这两个while和循环我有接收器? – CBennett

+0

这就是'两种情况'的意思,是的。 – EJP