-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPServer.java
More file actions
119 lines (107 loc) · 2.79 KB
/
TCPServer.java
File metadata and controls
119 lines (107 loc) · 2.79 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
import java.io.*;
import java.net.*;
import java.util.*;
public class TCPServer {
public static void main(String args[]) {
ServerSocket serverSocket = null;
Socket clientSocket = null;
int portNumber = 0;
String keyName = null;
int keyValue = 0;
for(int i=0; i<args.length;) {
switch(args[i]) {
case "-port" :
portNumber = Integer.parseInt(args[i+1]);
i += 2;
break;
case "-key" :
keyName = args[i+1];
i += 2;
break;
case "-value" :
keyValue = Integer.parseInt(args[i+1]);
i += 2;
break;
default:
System.err.println("Unknown parameter: " + args[i]);
i++;
}
}
if(portNumber == 0 || keyName == null) {
System.err.println("Incorrect execution syntax");
System.exit(1);
}
try {
System.out.println("Creating the main server socket at port " + portNumber);
serverSocket = new ServerSocket(portNumber);
System.out.println("Socket created");
}
catch (IOException e) {
System.err.println("Counldn't create a server socket: " + e);
System.exit(1);
}
while(true) try {
System.out.println("Waiting for a client");
clientSocket = serverSocket.accept();
System.out.println("A client connected from " + clientSocket.getInetAddress().toString() + ":" + clientSocket.getPort());
Scanner in = new Scanner(clientSocket.getInputStream());
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
String command = "";
String parameter = "";
String name = "";
int value = 0;
String input = "";
String output = "";
command=in.next();
input = command;
switch(command) {
case "GET":
parameter=in.next();
input += " " + parameter;
switch(parameter) {
case "NAMES":
output = "OK 1 " + keyName;
break;
case "VALUE":
name = in.next();
input += " " + name;
if(name.equals(keyName)) {
output = "OK " + keyValue;
} else {
output = "NA";
}
break;
default:
output = "NA";
}
break;
case "SET":
name = in.next();
input += " " + name;
if(name.equals(keyName)) {
value = in.nextInt();
input += " " + value;
keyValue = value;
output = "OK";
} else {
output = "NA";
}
break;
case "QUIT":
System.out.println("Terminating");
System.exit(0);
default:
output = "NA";
}
System.out.println("Parsed command: " + input);
System.out.println("Response: " + output);
out.println(output);
in.close();
out.close();
clientSocket.close();
}
catch (IOException e) {
System.err.println("Error at work: " + e);
}
}
}