我在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()
在客户端是正确的。
为什么会发生这种情况?
很难知道,但我敢打赌,问题出在您使用的网络上。您可以使用一些网络工具来检查实际的网络活动。 – m0skit0
它位于localhost上。港口6000 – BIfreak
如果你发布[SSCCE](http://sscce.org/),那将会更容易帮助你。 – mike