gpt4 book ai didi

通过套接字发送 .jpg 或图像时 Java 连接重置

转载 作者:行者123 更新时间:2023-12-02 05:15:11 24 4
gpt4 key购买 nike

我使用 java 程序通过套接字发送大型文本文档或其他文件没有任何问题,但是当我尝试发送 .jpg 文件或其他图像时,我收到 java.net.SocketException: 连接重置。

通过套接字发送 229 KB 文本文档时,我没有遇到任何问题,但当我尝试发送 89 KB 图像时,出现错误。我使用 while 循环来读取和写入文件。

这是有问题的服务器类的一部分(名为 EasyDataSend):

public EasyDataSend() throws IOException    
{
port = 8080;
server = new ServerSocket(port);

socket = server.accept();

dataOutputStream = new DataOutputStream(socket.getOutputStream());
}

public void sendFile(String path) throws IOException
{
File file = new File(path);

InputStream fileInputStream = new FileInputStream(file);
OutputStream fileOutputStream = socket.getOutputStream();

byte[] bytes = new byte[16 * 1024];

int count;
while ((count = fileInputStream.read(bytes)) > 0)
{
fileOutputStream.write(bytes, 0, count);
}

fileOutputStream.close();
fileInputStream.close();
socket.close();
server.close();
}

这是客户端类的一部分(名称 EasyDataReceive):

public EasyDataReceive() throws UnknownHostException, IOException
{
ip = "127.0.0.1";
port = 8080;
socket = new Socket(ip,port);
}

public void receiveFile(String path) throws IOException, SocketException
{
File file = new File(path);
InputStream fileInputStream = socket.getInputStream();
OutputStream fileOutputStream = new FileOutputStream(file);

byte[] bytes = new byte[16*1024];

int count;
while ((count = fileInputStream.read(bytes)) > 0)
{
fileOutputStream.write(bytes, 0, count);
}

fileOutputStream.close();
fileInputStream.close();
socket.close();

}

这是我得到的错误:

Exception in thread "main" java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) at java.net.SocketInputStream.read(Unknown Source) at java.net.SocketInputStream.read(Unknown Source) at EasyDataReceive.receiveFile(EasyDataReceive.java:111) at TesterClient.main(TesterClient.java:23)

此外,第 111 行实际上只是客户端类中 while 循环的开始。我不想将整个类(class)粘贴到帖子中。第 23 行只是我构建 EasyDataReceive 对象的测试类的一部分。

最佳答案

您的套接字应该位于方法内:receiveFile() 和 sendFile()。

例如,

public static void sendFile(String path) throws IOException {
try {
socket = new Socket("127.0.0.1", 8080);
System.out.println("Connected");
File file = new File(path);
InputStream fileInputStream = new FileInputStream(file);
OutputStream fileOutputStream = socket.getOutputStream();
byte[] bytes = new byte[16 * 1024];
int count;
while ((count = fileInputStream.read(bytes)) > 0) {
fileOutputStream.write(bytes, 0, count);
}
fileOutputStream.close();
fileInputStream.close();
} catch (UnknownHostException u) {
System.out.println(u);
} catch (IOException i) {
System.out.println(i);
} finally {
try {
socket.close();
} catch (IOException i) {
System.out.println(i);
}
}
}

或者您应该将套接字客户端传递给您的方法,即

private void receiveFile (Socket client) {
...
}

关于通过套接字发送 .jpg 或图像时 Java 连接重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56300802/

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