【发布时间】:2019-11-28 17:58:44
【问题描述】:
说明
此应用程序假定将文件传输到服务器,并且旨在从命令行运行。 -d 参数用于下载,-u 用于从/上传到服务器。
问题
主要问题是服务器应用启动后,第一个请求总是“搞砸”。
- 上传文件的开头缺失
- 下载进度百分比都是错误的
它只发生在服务器启动后的第一个请求,之后的所有其他请求都很好。
代码
- 服务器
主要
//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();
}
}
【问题讨论】:
-
我认为是 BufferedReader 但我不知道为什么。
-
正确。它提前读取,填充它的缓冲区,包括一些数据。对所有内容使用相同的
DataInput/OutputStreams。
标签: java sockets fileinputstream fileoutputstream