-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathftserver.java
More file actions
209 lines (196 loc) · 8.55 KB
/
ftserver.java
File metadata and controls
209 lines (196 loc) · 8.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import java.util.*;
import java.net.*;
import java.io.*;
/**
* ftserver: Server side of File Transfer System
* Description: The ftserver opens a socket on a user-specified port and waits for a client connection request. Once connected, the client
* either requests the current directory list of files or a specific file by name, along with a port to establish the data transfer connection
* on. Server opens and connects to the client on this new data connection to transfer the directory or file, sending an error message via
* the control connection in the case of an invalid command or non-existent file.
*
* @author Grace Thompson
* @date-started: 11/19/2016
* @last-modified: 11/20/2016
*/
public class ftserver
{
/* function to retrieve messages from client
* Parameters: BufferedReader input stream for receiving messages from client
* Returns: none
*/
private static String getMessage(BufferedReader in) {
String message = null;
try {
message = in.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return message;
}
/* function to send a short message to client
* Parameters: PrintWriter output stream for writing messages to client, String message to send
* Returns: none
*/
private static void sendMessage(PrintWriter out, String message) {
out.println(message);
out.flush();
}
/* function to get directory contents and send to the client via data port
* Parameters: PrintWriter output stream for writing directory to client
* Returns: none
*/
private static void sendDirectory(PrintWriter out) {
File currentDir = new File(".");
File[] list = currentDir.listFiles();
for(File f : list) {
if(f.isDirectory()) {
System.out.println(f.getName());
}
if(f.isFile()) {
System.out.println(f.getName());
sendMessage(out, f.getName()); //send file names to client
}
}
}
/* function to create data transfer connection to client
* Parameters: integer port to establish data connection, String name of file to send
* Returns: 1 on success, 0 on error (if file not found)
*
FileInputStream REFERENCE: File input stream reference https://www.mkyong.com/java/how-to-read-file-in-java-fileinputstream/
*/
private static int startDataConnection(String clientHost, int port, String filename) {
if (filename != null) {
System.out.println("File " + filename + " requested on port " + port);
System.out.println();
} else {
System.out.println("List directory requested on port " + port);
System.out.println();
}
//start new socket on port and accept client connection
try (
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
PrintWriter dataOut =
new PrintWriter(clientSocket.getOutputStream(), true);
) {
//System.out.println("Connection established on port " + port);
if (filename != null) {
//attempt to find specified file in current directory
File file = new File(filename);
int fileSize = 0;
//check if a file
if(file.exists() && !file.isDirectory()) {
//send file contents through connection
try (FileInputStream fis = new FileInputStream(file)) {
//System.out.println("Total file size to read (in bytes) : " + fis.available());
System.out.println("Sending " + filename + " to " + clientHost + ":" + port);
System.out.println();
fileSize = fis.available();
//send filesize to client so they know what to expect
dataOut.println(fileSize);
int content;
while ((content = fis.read()) != -1) {
//convert to char and display
//System.out.print((char) content);
dataOut.print((char) content);
}
//return 1; //successful data transfer
} catch (IOException e) {
e.printStackTrace();
}
return 1; //successful data transfer
} else {
//send error message to client, filesize 0 as signal of error
//System.out.println("Size of file/error: " + fileSize);
dataOut.println(fileSize);
return 2; //error
}
} else {
sendDirectory(dataOut);
return 1;//successful data transfer
}
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}
/*function to accept incoming connection to receive commands from client, closed from client side
* Parameters: ServerSocket socket to connect to client with (Connection P)
* Output: none
*/
private static void startControlConnection(ServerSocket socket, int port) {
try (
//accept incoming request to connect
Socket clientSocket = socket.accept();
//setup input/output streams
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
) {
//get hostname of client
String clientHost = clientSocket.getInetAddress().getHostName();
System.out.println("Connection from " + clientHost);
//receive command received from client
String command = getMessage(in);
//System.out.println("Command received: " + command);
//if valid command, initiate TCP data connection with client on client-specified port
int dataPort;
String requestFile = null;
if (command.equals("-l")) {
//get data port number
dataPort = Integer.parseInt(getMessage(in));
} else if (command.equals("-g")) {
requestFile = getMessage(in);
//System.out.println("File name: " + requestFile);
//get data port number
dataPort = Integer.parseInt(getMessage(in));
} else {
//invalid command received, send back error message to client
String message = "Invalid Command Received";
sendMessage(out, message);
return;
}
//send acknowledgement of valid command
sendMessage(out, "1");
//open new socket connection on data port and send requested file/list
int success = startDataConnection(clientHost, dataPort, requestFile);
//if error (2), print file not found
if (success == 2) {
String error = "File Not Found";
System.out.println("File not found. Sending error message to " + clientHost + ":" + port);
sendMessage(out, error);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//check port number specified from command line as first argument
if (args.length < 1) {
System.out.println("ERROR: Must specify port argument.");
return;
}
// int port = Integer.parseInt(args[0]);
int port = -1;
//validate port
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.out.println("ERROR: Must specify valid port");
}
//create socket with port number to wait for incoming connections
try (
ServerSocket serverSocket = new ServerSocket(port);
) {
//infinite loop until SIGINT is received
while (true) {
System.out.println("Server open on " + port);
//try to accept incoming connection to client
startControlConnection(serverSocket, port);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}