-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathServer.java
More file actions
76 lines (68 loc) · 2.13 KB
/
Copy pathServer.java
File metadata and controls
76 lines (68 loc) · 2.13 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
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Server {
private ServerSocket serverSocket = null;
private Socket s = null;
private ObjectOutputStream objos = null;
private int port = 5000;
// returns port
String getPort() {
return Integer.toString(port);
}
// responsible for starting the server
public boolean startServer() throws UnknownHostException, IOException {
serverSocket = new ServerSocket(port);
System.out.println(
"Server started on " + InetAddress.getLocalHost().getHostAddress() + ":" + port + " at " + new Date());
return true;
}
// responsible for client connection
private boolean acceptClient() throws IOException {
System.out.println();
System.out.println("Waiting for client to connect since\t" + new Date());
s = serverSocket.accept();
System.out.println("New client connected at\t\t\t" + new Date());
return true;
}
// responsible for distributing the paper
private boolean serveClient() throws IOException {
System.out.println("Atteding to distribute paper at\t\t" + new Date());
objos = new ObjectOutputStream(s.getOutputStream());
AttendExam attendExam = new AttendExam();
objos.writeObject(attendExam);
return true;
}
// keeps the server live
public void liveServer() throws IOException, InterruptedException {
while (true) {
acceptClient();
serveClient();
}
}
public static void main(String[] args) {
Server server = new Server();
try {
if (args.length == 0)
server.startServer();
server.liveServer();
} catch (BindException e) {
System.out.println("Server starting falied !");
e.printStackTrace();
} catch (UnknownHostException e) {
args[0] = server.getPort();
main(args);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
System.out.println("Exiting at... " + new Date());
} catch (Exception e) {
e.printStackTrace();
}
}
}