-
Notifications
You must be signed in to change notification settings - Fork 0
/
TCPClient.java
362 lines (315 loc) · 9.41 KB
/
TCPClient.java
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import java.net.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;
import java.text.SimpleDateFormat;
public class TCPClient
{
//A 4KB buffer to receive server messages.
final static int BUF_LEN = 4096;
final static int EXP_FIELDS = 1;
final static int TIMEOUT = 2000;
public static String parseCommand(String str)
{
String method, txn_id = "-1", seq_num = "0", content_length = "0", data = "";
String[] result = str.split("\\s+");
String content = "";
String message = null;
String header = null;
if(result.length < EXP_FIELDS)
{
System.out.print("Wrong format.");
System.out.println("A request header must have at least " +
EXP_FIELDS + " fields");
return null;
}
System.out.println("==========================================");
for (int x=0; x<result.length; x++)
{
switch(x)
{
case 0:
System.out.print("Method:\t\t\t");
break;
case 1:
System.out.print("Txn ID:\t\t\t");
break;
case 2:
System.out.print("Sequence Number:\t");
break;
case 3:
System.out.print("Content Length: \t");
break;
case 4:
System.out.print("Data:\t\t\t");
break;
default:
System.out.print("Unknown Field:\t");
break;
}
System.out.println(result[x]);
}
System.out.println("==========================================");
method = result[0];
if(result.length > 1)
txn_id = result[1];
if(result.length > 2)
seq_num = result[2];
if(result.length > 3)
content_length = result[3];
if(result.length > 4)
data = result[4];
/* Check if the method is valid */
if(method.equals("WRITE") || method.equals("write"))
method = "WRITE";
if(method.equals("NEW_TXN") || method.equals("new_txn"))
method = "NEW_TXN";
if(method.equals("COMMIT") || method.equals("commit"))
method = "COMMIT";
if(method.equals("ABORT") || method.equals("abort"))
method = "ABORT";
if(method.equals("READ") || method.equals("read"))
method = "READ";
if(!method.equals("WRITE") &&
!method.equals("NEW_TXN") &&
!method.equals("COMMIT") &&
!method.equals("ABORT") &&
!method.equals("READ"))
{
System.out.println("Invalid method:");
System.out.println(result[0]);
return null;
}
if((new Integer(seq_num)).intValue() < 0)
{
System.out.println("Sequence number must be non-negative");
return null;
}
if(method.equals("NEW_TXN"))
{
System.out.println("Looks like your method is \"NEW_TXN\"." +
"I will generate a file name for this transaction.");
content = "test_file.txt";
content_length = (new Integer(content.length())).toString();
}
if(method.equals("WRITE"))
{
System.out.println("Looks like your method is \"WRITE\"." +
"I will generate some content to send to the server.");
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
content = method + " " + txn_id + " " + seq_num + " " +
content_length + " " +
sdf.format(date) + "\n";
content_length = (new Integer(content.length())).toString();
}
if(method.equals("READ"))
{
System.out.println("Looks like your method is \"READ\"." +
"I will request the file " + data + " from the server.");
content_length = (new Integer(data.length())).toString();
content = data;
}
/* Now create a string to send to the server */
header = method + " " + txn_id + " " + seq_num + " " + content_length +
"\r\n\r\n";
/* If the method is not WRITE, NEW_TXN or READ, this is the message without data. It has
* two blank lines at the end.
*/
if(!method.equals("WRITE") && !method.equals("NEW_TXN") && !method.equals("READ"))
{
header = header + "\r\n";
}
message = header+content;
System.out.println("=======================");
System.out.println("MESSAGE SENT TO SERVER:");
System.out.println("====> begin message");
System.out.print(message);
System.out.println("====> end message");
return message;
}
public static void processAndSend(Socket s, String str) throws IOException
{
BufferedInputStream in = new BufferedInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
byte b[] = new byte[BUF_LEN];
int bytesRead = 0;
String toSend = parseCommand(str);
if(toSend == null)
return;
try
{
out.writeBytes(toSend + "\n");
}
catch( IOException ioe)
{
System.out.println("Could not send message to the server: " + ioe.getMessage());
return;
}
/* Try to read a response from the server. Time out. */
s.setSoTimeout(TIMEOUT);
System.out.println("Received from server:");
try
{
while( (bytesRead = in.read(b, 0, BUF_LEN)) > 0)
{
/* Display non-printable characters */
for(int i = 0; i < bytesRead; i++)
{
/*
if(b[i] < 32 || b[i] > 126)
System.out.println("Unprintable character " + b[i] + ".");
*/
}
b[bytesRead] = (byte)'\0';
System.out.print(new String(b));
bytesRead = 0;
}
System.out.println();
}
catch(SocketException se)
{
if(se.getMessage().equals("Connection reset"))
return;
else
{
System.out.println("Could not read from or write to the socket: " + se.getMessage());
return;
}
}
catch(SocketTimeoutException ste)
{
System.out.println("Timed out after " + TIMEOUT +
"ms. No more bytes are coming from the server.");
}
catch(ArrayIndexOutOfBoundsException aie)
{
if(bytesRead < 0 )
System.out.println("Error reading data from the server: " + aie.getMessage() );
else
{
//This is most probably due to a buffer overflow.
System.out.println("The message sent by the server is larger than the receive buffer.");
//Replace the last byte in the buffer with the null termination character
//and display part of the received contents
b[(BUF_LEN - 1)] = '\0';
System.out.println("Buffer Contents: ");
System.out.println(new String(b));
}
}
s.setSoTimeout(0);
}
public static void main (String args[])
{
Socket s = null;
BufferedReader in;
printHelpMessage();
try
{
int serverPort = 7896;
if(args.length >1)
{
try
{
serverPort = (new Integer(args[1])).intValue();
}
catch(NumberFormatException nfe)
{
System.out.println("Invalid port: " + args[1]);
System.exit(0);
}
if(serverPort < 0 || serverPort > 65536)
{
System.out.println("Invalid port: " + args[1]);
System.exit(0);
}
}
String server = "localhost";
if(args.length > 0)
server = args[0];
System.out.println("Hello. Will listen on " + server + ":" + serverPort);
in = new BufferedReader(new InputStreamReader(System.in));
/* Keep reading commands */
while (true)
{
s = new Socket(server, serverPort);
System.out.print("Enter command> ");
String str = in.readLine();
if(str == null)
break;
if(str.equals("exit"))
break;
if(str.equals("help"))
{
printHelpMessage();
continue;
}
processAndSend(s, str);
s.close();
}
}
catch (UnknownHostException e)
{
System.out.println("Socket:"+e.getMessage());
}
catch (EOFException e)
{
System.out.println("EOF:"+e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
finally
{
if(s!=null)
try
{
s.close();
}
catch (IOException e)
{
System.out.println("close:"+e.getMessage());
}
System.out.println("Exiting. Good-bye!");
}
}
public static void printHelpMessage()
{
System.out.println("\nUse this program to send valid Assignment 2 protocol messages "
+ "to your server.");
System.out.println("There are two command line arguments: hostname and port.");
System.out.println("Default values for hostname and port are: localhost:7896");
System.out.println("The program will display a command prompt.");
System.out.println("Enter commands at the prompt to send A2 protocol messages to " +
"your server");
System.out.println("To send a NEW_TXN message, type:");
System.out.println("\t new_txn");
System.out.println("To send a WRITE message, type:");
System.out.println("\t write <txn_num> <seq_num>");
System.out.println("For example:");
System.out.println("\t write 1 1");
System.out.println("The program will generate some content for you");
System.out.println("To send a COMMIT message, type:");
System.out.println("\t commit <txn_num> <seq_num>");
System.out.println("For example:");
System.out.println("\t commit 1 1");
System.out.println("To send an ABORT message, type:");
System.out.println("\t abort <txn_num> <seq_num>");
System.out.println("For example:");
System.out.println("\t abort 1 1");
System.out.println("To send a READ message, type:");
System.out.println("\t read <any txn id> <any non-neg seq_num> <any content_length> <file_name>");
System.out.println("For example:");
System.out.println("\t read 1 1 1 file.txt");
System.out.println("(The correct content length will be computed automatically and send to the server.");
System.out.println("The program will display the message sent to the server.");
System.out.println("Then it will wait for response from the server.");
System.out.println("It will time out after 1 second if there is no response.");
System.out.println("You can send as many messages as you want.");
System.out.println("To exit, type \"exit\"");
System.out.println("To display this message again, type \"help\"\n");
}
}