2016-11-22 19 views
0

我在Java中有一个套接字问题。我已经实现了服务器和客户端进行通信并将文件从客户端发送到服务器。 问题是,有时方法in.read(buffer)给我-1而不是真正的文件长度。它几乎是随机发生的。Java - 套接字和文件发送/接收正在随机工作

服务器部分:

InputStream in = socket.getInputStream(); 
OutputStream out = new FileOutputStream(file); 
System.out.println("Server: Will receive file..."); 
byte[] buffer = new byte[4096]; 
int length = in.read(buffer); 
System.out.println("Server: will get " + length + " byte"); 

while (length > 0){ 
    out.write(buffer, 0, length); 
    System.out.println("Server: reading !"); 
    length = in.read(buffer); 
} 

System.out.println("Server: got file, length: " + file.length()); 

in_code.close(); 
out.close(); 
in.close(); 

客户:

public void sendFileToServer(String s) throws IOException{ 
    try{ 
     clientSocket = new Socket(ip, port); 
    }catch (Exception e){ 
     e.printStackTrace(); 
    } 

    File file = new File(s); 
    String filename = file.getName(); 
    this.sendCode(filename); 

    // Get the size of the file 
    long length = file.length(); 

    System.out.println("Client: send file name: " +filename); 
    System.out.println("Client: send file length: " +length); 

    byte[] bytes = new byte[1024]; 
    InputStream in = new FileInputStream(file); 
    OutputStream out = clientSocket.getOutputStream(); 
    int count; 

    while ((count = in.read(bytes)) > 0) { 
     System.out.println("Client send !!!"); 
     out.write(bytes, 0, count); 
    } 

    out.close(); 
    in.close(); 
    this.clientSocket.close(); 
} 

服务器部分是在同时,当然循环。无法全部粘贴,因为它有很多代码。

因此,客户端正在调用sendFileToServer()方法 - 比方说5次。一个又一个在一个循环中。 有时服务器获取所有文件都是正确的,有时某些文件是0,因为in.read(buffer)给出-1。但另一方面in.read()在客户端是正确的。

为什么会发生这种情况?

+0

很难知道,但我敢打赌,问题出在您使用的网络上。您可以使用一些网络工具来检查实际的网络活动。 – m0skit0

+0

它位于localhost上。港口6000 – BIfreak

+0

如果你发布[SSCCE](http://sscce.org/),那将会更容易帮助你。 – mike

回答

0

InputStream#read(byte[])的状态的文档:

[该方法返回]读取的字节的总数到缓冲器, 或-1,如果没有更多的数据,因为流的末尾一直 到达。

所以如果方法返回-1,这不是网络错误。这是表示Socket或Input/OutputStream已关闭的标准行为。

我不知道你的整个服务器代码,但似乎你正试图在服务器端重新使用先前关闭的套接字。

+0

我同意他的设计有缺陷,但'sendFileToServer'每次都会创建一个新的Socket。我想,因为他还说客户端代码不会产生'-1',服务器端的客户端接受代码错误。 – mike