-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerThread.java
More file actions
58 lines (46 loc) · 1.6 KB
/
Copy pathServerThread.java
File metadata and controls
58 lines (46 loc) · 1.6 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.*;
import java.net.Socket;
/*
* 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 socket;
ObjectOutputStream output = null;
ObjectInputStream input = null;
public ServerThread(Socket socket) {
this.socket = socket;
}
public void run() {
System.out.print("Accepted connection. ");
try {
output = new ObjectOutputStream(socket.getOutputStream());
//opens a BufferedReader on the socket
input = new ObjectInputStream(socket.getInputStream());
System.out.print("Reader and writer created. ");
// read the command from the client
int command = input.readInt();
System.out.println("Read command " + command);
Object outObject = Server.getCommandList()[command].apply(input.readObject());
System.out.println("Server sending result to client");
// send the result of the command to the client
output.writeObject(outObject);
output.close();
input.close();
}
catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
finally {
// close the connection to the client
try {
socket.close();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("Output closed.");
}
}
}