-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTCPClient.java
More file actions
99 lines (86 loc) · 2.66 KB
/
TCPClient.java
File metadata and controls
99 lines (86 loc) · 2.66 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
import java.util.*;
import java.net.*;
import java.io.*;
public class TCPClient {
public static void main(String[] args) {
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
InetAddress address = null;
int port = 0;
String command = "";
for(int i=0; i<args.length;) {
switch(args[i]) {
case "-address":
try {
address = InetAddress.getByName(args[i+1]);
} catch (UnknownHostException e) {
System.err.println("Unknown host: " + args[i+1]);
}
i += 2;
break;
case "-port":
port = Integer.parseInt(args[i+1]);
i +=2;
break;
case "-command":
i++;
command = args[i++];
String parameter = "";
String name = "";
int value = 0;
switch(command) {
case "GET":
parameter=args[i++];
command += " " + parameter;
if(parameter.equals("NAMES")) {
} else if(parameter.equals("VALUE")) {
name = args[i++];
command += " " + name;
} else {
System.err.println("Unknown: " + parameter);
}
break;
case "SET":
name = args[i++];
value = Integer.parseInt(args[i++]);
command += " " + name + " " + value;
break;
case "QUIT":
break;
default:
System.err.println("Unknown: " + command);
}
break;
default:
System.err.println("Unknown parameter: " + args[i]);
i++;
}
}
if(address == null || port == 0 || command.equals("")) {
System.err.println("Incorrect execution syntax");
System.exit(1);
}
try {
System.out.println("Creating a client socket");
socket = new Socket(address, port);
System.out.println("Socket created");
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Sending " + command + " as a request");
out.println(command);
if(! command.equals("QUIT")) {
String response = "";
System.out.println("Waiting for a response");
response = in.readLine();
System.out.println(response);
}
out.close();
in.close();
socket.close();
} catch(IOException e) {
System.err.println("Error at work: " + e);
System.exit(1);
}
}
}