gpt4 book ai didi

java - 尝试传输文件时套接字关闭异常

转载 作者:可可西里 更新时间:2023-11-01 02:50:26 26 4
gpt4 key购买 nike

我正在尝试使用 Java 和 TCP 将文件从服务器传输到客户端,但是在客户端我收到套接字关闭异常,而服务器在尝试传输文件时没有错误。我对这个错误感到困惑,因为我在尝试读取它之前没有关闭套接字。服务器接受连接并发送文件,但客户端收到该错误。有什么建议吗?

错误是:

java.net.SocketException: Socket closed

服务器线程的运行函数:

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();

最佳答案

此套接字的输入流在变量in 中可用

InputStream in = socket.getInputStream();

所以

 Change is.read(contents)) to in.read(contents)) 

关于java - 尝试传输文件时套接字关闭异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com