0

我正在编写一个自定义协议。我有一个命令名称,代码如下所示。

if(commandString.equals("PUT")){
    File f = new File(currentFolder, "test.txt");
    if(!f.exists())
         f.createNewFile();
    FileOutputStream fout = new FileOutputStream(f);
    long size = 150;
    long count = 0;
    int bufferLeng = 0;
    byte[] buffer = new byte[512];
    while((bufferLeng = dis.read(buffer))>0) //dis is a data input stream.
    {
        count =+ bufferLeng;
        fout.write(buffer);
    }
    System.out.println("All Good");
    fout.flush();
    fout.close();

}

该命令由客户端发送到服务器,如下所示pWriter.println("PUT");。现在我运行它,它确实创建了文件test.txt,但随后被冻结,服务器不显示 All Good 消息。为什么会这样?什么是简单的解决方法?

服务器和客户端工作!

谢谢

4

2 回答 2

1

服务器等待客户端关闭套接字。这将传输导致dis.read()返回 -1 的文件结尾。

通常,这不是您想要的。解决方案是在数据之前发送文件大小,然后准确读取该数据量。

确保您的客户端在写入文件数据的最后一个字节后调用socket.flush(),否则数据可能会卡在缓冲区中,这也会导致服务器挂起。

于 2013-09-16T14:56:43.877 回答
0

也许消除dis.read(buffer)并使用以下内容。

if(commandString.equals("PUT")){
    File f = new File(currentFolder, "test.txt");
    if(!f.exists())
         f.createNewFile();
    FileOutputStream fout = new FileOutputStream(f);
    long size = 150;
    long count = 0;

    byte[] buffer = new byte[512];
    int bufferLeng = buffer.length;
    while(count < size && bufferLeng>0) //dis is a data input stream.
    {

        fout.write(buffer);
        count =+ bufferLeng;
    }
    System.out.println("All Good");
    fout.flush();
    fout.close();

}

这应该工作

于 2013-09-16T15:20:01.193 回答