使用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();
}
这是我得到的错误:
线程“ main”中的异常java.net.SocketException:连接重置 在java.net.SocketInputStream.read(未知来源) 在java.net.SocketInputStream.read(未知来源) 在java.net.SocketInputStream.read(未知来源) 在EasyDataReceive.receiveFile(EasyDataReceive.java:111) 在TesterClient.main(TesterClient.java:23)
此外,第111行实际上只是客户端类中while循环的开始。我不想将整个课程粘贴到帖子中。第23行只是构建EasyDataReceive对象的测试类的一部分。
答案 0 :(得分:0)
您的套接字应位于以下方法之内: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) {
...
}