gpt4 book ai didi

java - 文件传输服务器 <-> 客户端,文件不完整

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

描述

该应用程序应该在服务器之间传输文件,并且应该从命令行运行。 -d 参数用于下载,-u 用于从服务器上传/上传到服务器。

问题

主要问题是服务器应用程序启动后,第一个请求总是“困惑”。

  • 上传时文件开头丢失
  • 下载进度百分比都是错误的

1

只有服务器启动后的第一个请求才会发生这种情况,此后的所有其他请求都完全正常。

代码

  • 服务器

主要

//Jaroslaw Janas
//17436176

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Main {

public static void main(String[] args){
new Main();
}

private Main(){
ServerSocket servSoc = null;
try {
servSoc = new ServerSocket(4400);
} catch (IOException e) {
System.out.println("Failed to start the server");
e.printStackTrace();
System.out.println("Closing the server...");
System.exit(0);
}

System.out.println("Server running");
System.out.println("Awaiting connections...");
System.out.println("---------------");
while(true){
try {
Socket clientSocket = servSoc.accept();
new Connection(clientSocket).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

连接

//Jaroslaw Janas
//17436176

import java.io.*;
import java.lang.reflect.Field;
import java.net.Socket;

public class Connection extends Thread {

private Socket soc;
Connection(Socket soc){
this.soc = soc;
}

@Override
public void run(){
// <<<<<<<<<<<<<<<<<<<< SETUP >>>>>>>>>>>>>>>>>>>>
String str = "Received a connection from: "
+ soc.getRemoteSocketAddress().toString();
System.out.println(str);

// Get arguments
String operation = null;
String filename = null;

BufferedReader br = null;
try {
br= new BufferedReader(new InputStreamReader(soc.getInputStream()));
operation = br.readLine();
filename = br.readLine();


} catch (IOException e) {
System.out.println("Failed to initialize BufferedReader");
e.printStackTrace();
System.out.println("Closing the server...");
System.exit(0);
}

// <<<<<<<<<<<<<<<<<<<< UPLOAD>>>>>>>>>>>>>>>>>>>>

// Upload from client
if(operation.equalsIgnoreCase("u")){
System.out.println("Upload request for" + filename);

// Create new file
File f = new File("files/"+filename);

// Set up FileInputStream
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException e) {
System.out.println("Failed to set up the FileOutputStream");
e.printStackTrace();
}

System.out.println("Receiving the file from " + soc.getRemoteSocketAddress().toString());
// Set up the InputStream for receiving the file
InputStream is = null;
try {
assert fos != null;
is = soc.getInputStream();

byte[] bytes = new byte[8*1024];
int count;
while ((count = is.read(bytes)) > 0) {
fos.write(bytes, 0, count);
}

System.out.println("File " + filename + " received");
is.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}


}

// <<<<<<<<<<<<<<<<<<<< DOWNLOAD >>>>>>>>>>>>>>>>>>>>

// Download from client
else if(operation.equalsIgnoreCase("d")){
System.out.println("Download request for " + filename);

// set up the stream
PrintStream ps = null;
try {
ps = new PrintStream(soc.getOutputStream());
} catch (IOException e) {
System.out.println("Failed to configure the PrintStream");
e.printStackTrace();
}

// read the file
File f = new File("files/"+filename);
FileInputStream fip = null;
try {
fip = new FileInputStream(f);
} catch (FileNotFoundException e) {
System.out.println("Did not find the file");
e.printStackTrace();
}

System.out.println("Sending the file to " + soc.getRemoteSocketAddress().toString());
// Send the file
try {
assert fip != null;

byte[] bytes = new byte[8*1024];
int count;
while ((count = fip.read(bytes)) > 0) {
assert ps != null;
ps.write(bytes, 0, count);
}

System.out.println("File " + filename + " sent");
} catch (IOException e) {
System.out.println("Failed to read the file");
e.printStackTrace();
}

// close stuff
assert ps != null;
ps.flush();
ps.close();
}
else{
System.out.println("Incorrect request");
}

// <<<<<<<<<<<<<<<<<<<< CLOSE CONNECTION >>>>>>>>>>>>>>>>>>>>
try {
br.close();
soc.close();
System.out.println("Connection " + soc.getRemoteSocketAddress().toString() + " closed");
System.out.println("---------------");
} catch (IOException e) {
e.printStackTrace();
}
}

}

  • 客户端

主要

//Jaroslaw Janas
//17436176

import java.io.IOException;
import java.net.Socket;

public class Main {

public static void main (String[] args){
new Main(args);
}

private Main(String[] args){
int port;
String ip, operation, filePath;

ip = args[0];
port = Integer.parseInt(args[1]);
operation = args[2];
filePath = args[3];

System.out.println(ip + " " + port + " " + operation + " " + filePath);

Socket soc;
try {
System.out.println("Connecting to the server...");
soc = new Socket(ip, port);
} catch (IOException e) {
System.out.println("Could not connect to the server");
e.printStackTrace();
System.out.println("Stopping the client");
return;
}

System.out.println("Connected to " + soc.getRemoteSocketAddress().toString());

if(operation.equalsIgnoreCase("-u")){
System.out.println("Configuring the upload");
new Upload(soc, filePath);
}
else if(operation.equalsIgnoreCase("-d")){
System.out.println("Configuring the download");
new Download(soc, filePath);
}
else{
System.out.println("Invalid argument " +operation);
}
}
}

连接

//Jaroslaw Janas
//17436176

import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;

abstract class Connection {

private Socket soc;
PrintStream ps;
String filename;

Connection(Socket soc, String filePath, String operation){
this.soc = soc;
filename = getFilePathFileName(filePath);

// set up the the stream used for sending arguments
try {
ps = new PrintStream(soc.getOutputStream());
} catch (IOException e) {
System.out.println("Failed to configure the connection");
e.printStackTrace();
}

// send arguments
ps.println(operation);
ps.println(filename);
}

private String getFilePathFileName(String filepath){
String[] str = filepath.split("/");
return str[str.length-1];
}

public void connectionClose(){
ps.flush();
ps.close();

try {
soc.close();
System.out.println("Connection closed");
} catch (IOException e) {
e.printStackTrace();
}
}
}

上传

//Jaroslaw Janas
//17436176

import java.io.*;
import java.net.Socket;

class Upload extends Connection {

Upload(Socket soc, String filePath) {
super(soc, filePath, "u");

// Read the file
File f = new File(filePath);
FileInputStream fip = null;
try {
fip = new FileInputStream(f);
} catch (FileNotFoundException e) {
System.out.println("Did not find the file");
e.printStackTrace();
System.out.println("Closing the client");
System.exit(0);
}

// Send the file to the server
try {
System.out.println("Uploading...");

byte[] bytes = new byte[8 * 1024];
float fileSize = fip.available();

int progress = 0;
int count;
while ((count = fip.read(bytes)) > 0) {
ps.write(bytes, 0, count);

progress += (count / fileSize) * 100;
System.out.println(progress + "%");

}

System.out.println("Upload completed");
} catch (IOException e) {
System.out.println("Failed to upload " + filename);
e.printStackTrace();
}

// Close the connection
connectionClose();
}
}

下载

//Jaroslaw Janas
//17436176

import java.io.*;
import java.net.Socket;

class Download extends Connection{

Download(Socket soc, String filePath){
super(soc, filePath, "d");

// Create a new file
File f = new File("files/"+filename);

// Set up FileOutputStream - outputs to the file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
} catch (FileNotFoundException e) {
System.out.println("Failed to set up the FileOutputStream");
e.printStackTrace();
}

// Download the file
InputStream is;
try {
assert fos != null;

System.out.println("Downloading...");

// Set up the InputStream for downloading the file
// from the server
is = soc.getInputStream();

byte[] bytes = new byte[8*1024];
float fileSize = is.available();

int progress=0;
int count;
while ((count = is.read(bytes)) > 0) {
fos.write(bytes, 0, count);

progress += (count/fileSize) * 100;
System.out.println(progress +"%");
}

System.out.println("File " + filename + " downloaded");
is.close();
fos.close();
} catch (IOException e) {
System.out.println("Failed to download " + filename);
e.printStackTrace();
}

// Close the connection
connectionClose();
}
}

最佳答案

已修复。这是我将 dis = new DataInputStream()dis.readLine()

一起使用的 BufferReader

对于下载来说,这是完全不相关的东西。我试图获取从服务器发送到客户端的文件的文件大小。返回 0,因为文件尚未发送。我通过在发送实际文件之前发送文件的大小来修复它。

服务器

连接

//        <<<<<<<<<<<<<<<<<<<< SETUP >>>>>>>>>>>>>>>>>>>>
String str = "Received a connection from: "
+ soc.getRemoteSocketAddress().toString();
System.out.println(str);

// Get arguments
String operation = null;
String filename = null;

DataInputStream dis = null;
try {
dis = new DataInputStream(soc.getInputStream());
operation = dis.readLine();
filename = dis.readLine();

} catch (IOException e) {
System.out.println("Failed to initialize the DataInputStream");
e.printStackTrace();
}

...

//        Send the file
try {
assert fip != null;

ps.println(fip.available());
byte[] bytes = new byte[8*1024];
int count;
while ((count = fip.read(bytes)) > 0) {
ps.write(bytes, 0, count);
}
fip.close();

System.out.println("File " + filename + " sent");
} catch (IOException e) {
System.out.println("Failed to read the file");
e.printStackTrace();
}

客户端

下载

//        Download the file
DataInputStream dis;
try {
assert fos != null;

System.out.println("Downloading "+filename);

// Set up the DataInputStream for downloading the file
// from the server
dis = new DataInputStream(soc.getInputStream());

byte[] bytes = new byte[8*1024];
float fileSize = Float.parseFloat(dis.readLine());

int progress=0;
int count;
while ((count = dis.read(bytes)) > 0) {
fos.write(bytes, 0, count);

progress += (count/fileSize) * 100;
System.out.println(progress +"%");
}

System.out.println("File " + filename + " downloaded");
dis.close();
fos.close();
} catch (IOException e) {
System.out.println("Failed to download " + filename);
e.printStackTrace();
}

关于java - 文件传输服务器 <-> 客户端,文件不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59094246/

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