gpt4 book ai didi

java - 通过套接字发送文件

转载 作者:行者123 更新时间:2023-12-04 19:47:47 24 4
gpt4 key购买 nike

您好,我正在尝试使用 Java 中的客户端-服务器类发送文件。出于某种原因,当调用发送文件的方法时,套接字关闭。这是代码:

FileInputStream fIn = new FileInputStream(file);
out = new BufferedOutputStream(clientSocket.getOutputStream());
byte fileContent[] = new byte[(int) file.length()];
fIn.read(fileContent);
for (byte b : fileContent) {
out.write(b);
}

和来自客户端的代码:
FileOutputStream fIn = new FileOutputStream("testing");
BufferedInputStream inAout = new BufferedInputStream(clientSocket.getInputStream());
byte fileContent[] = new byte[1000000];
inAout.read(fileContent);
fIn.write(fileContent);

以及我收到的错误消息:严重:空
java.net.SocketException: 套接字关闭

我在这方面并没有真正的经验,所以如果有任何帮助,那就太好了。

最佳答案

InputStream.read(byte[]) 方法返回 int对于它实际读取的字节数。不能保证读取的字节数与您从字节数组中请求的一样多。它通常会返回底层缓冲区的大小,您将不得不多次调用它。

您可以通过将字节从套接字流式传输到文件而不是在内存中缓冲整个字节数组来提高效率。同样在服务器端,你可以做同样的事情来节省内存并且比一次写入一个字节更快。

这是一个服务器和客户端连接到自身以传输文件的工作示例:

public class SocketFileExample {
static void server() throws IOException {
ServerSocket ss = new ServerSocket(3434);
Socket socket = ss.accept();
InputStream in = new FileInputStream("send.jpg");
OutputStream out = socket.getOutputStream();
copy(in, out);
out.close();
in.close();
}

static void client() throws IOException {
Socket socket = new Socket("localhost", 3434);
InputStream in = socket.getInputStream();
OutputStream out = new FileOutputStream("recv.jpg");
copy(in, out);
out.close();
in.close();
}

static void copy(InputStream in, OutputStream out) throws IOException {
byte[] buf = new byte[8192];
int len = 0;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
}

public static void main(String[] args) throws IOException {
new Thread() {
public void run() {
try {
server();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();

client();
}
}

关于java - 通过套接字发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6099636/

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