【发布时间】:2018-05-18 09:01:45
【问题描述】:
我正在尝试使用 Java 和 TCP 将文件从服务器传输到客户端,但是在客户端我收到套接字关闭异常,而服务器在尝试传输文件时没有错误。我对这个错误感到困惑,因为我在尝试读取之前没有关闭套接字。服务器接受连接并发送文件,但客户端收到该错误。有什么建议吗?
错误是:
java.net.SocketException: 套接字关闭
服务器线程的运行函数:
public void run() {
System.out.println("Service thread running for client at " + socket.getInetAddress() + " on port " + socket.getPort());
try {
File file = new File("hank.txt");
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = socket.getOutputStream();
byte[] contents;
long fileLength = file.length();
long current = 0;
long start = System.nanoTime();
while(current!=fileLength) {
int size = 1000;
if(fileLength - current >= size) {
current += size;
}
else {
size = (int)(fileLength - current);
current = fileLength;
}
contents = new byte[size];
bis.read(contents,0,size);
os.write(contents);
System.out.println("sending file..." + (current*100)/fileLength+"% complete!");
}
os.flush();
this.socket.close();
}catch(Exception e) {
e.printStackTrace();
}
}
客户端接收文件代码:
System.out.println("Going to get the file...");
socket = new Socket(response.getIP().substring(1), response.getPort());
byte[] contents = new byte[10000];
FileOutputStream fos = new FileOutputStream("hank.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
InputStream in = socket.getInputStream();
int bytesRead = 0;
System.out.println("Starting to read file...");
while((bytesRead = is.read(contents))!=-1) { //the error points to this lin
bos.write(contents,0,bytesRead);
}
bos.flush();
bos.close();
in.close();
//
socket.close();
【问题讨论】:
-
将 is.read(contents)) 改为 in.read(contents))
-
非常感谢您修复了它。我有一个名为“is”的 ObjectInputStream,所以它没有红色下划线。我永远不会发现
-
查看Java multiple file transfer over socket以获得更好的代码。
标签: java sockets networking tcp