-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerThread.java
More file actions
58 lines (50 loc) · 1.52 KB
/
ServerThread.java
File metadata and controls
58 lines (50 loc) · 1.52 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicInteger;
/*
* Individual ServerThread listens for the client to tell it what command to run, then
* runs that command and sends the output of that command to the client
*
*/
public class ServerThread extends Thread {
Socket client = null;
PrintWriter output;
BufferedReader input;
public ServerThread(Socket client) {
this.client = client;
}
public void run() {
System.out.print("Accepted connection. ");
try {
// open a new PrintWriter and BufferedReader on the socket
output = new PrintWriter(client.getOutputStream(), true);
input = new BufferedReader(new InputStreamReader(client.getInputStream()));
System.out.print("Reader and writer created. ");
String inString;
// read the command from the client
while ((inString = input.readLine()) == null);
System.out.println("Read command " + inString);
// run the command using CommandExecutor and get its output
String outString = CommandExecutor.run(inString);
System.out.println("Server sending result to client");
// send the result of the command to the client
output.println(outString);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
// close the connection to the client
try {
client.close();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Output closed.");
}
}
}