-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEchoClient.java
More file actions
83 lines (74 loc) · 2.49 KB
/
EchoClient.java
File metadata and controls
83 lines (74 loc) · 2.49 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
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Date;
import java.text.SimpleDateFormat;
public class EchoClient extends Thread {
private static int i = 0;
private static SimpleDateFormat formatter = new SimpleDateFormat("[hh:mm:ss]");
private int id;
private SocketChannel clientSocket;
private ByteBuffer byteBuffer;
private String stringToSend;
public EchoClient(String newStringToSend){
this.id = i;
i++;
this.stringToSend = format(newStringToSend);
try {
clientSocket = SocketChannel.open(new InetSocketAddress(5672));
byteBuffer = ByteBuffer.allocate(512);
}
catch (Exception e){
e.printStackTrace();
}
}
public void run(){
sendMessage();
System.out.println(formatter.format(new Date()) + "[CLIENT " + id + "] Just sent the message: " + stringToSend);
String response = readResponse();
System.out.println(formatter.format(new Date()) + "[CLIENT " + id + "] Server response: " + response);
try{
clientSocket.close();
}
catch(Exception e){
e.printStackTrace();
}
System.out.println(formatter.format(new Date()) + "[CLIENT " + id + "] Connection with the server closed.");
}
private void sendMessage(){
byteBuffer.put(stringToSend.getBytes());
byteBuffer.flip();
while(byteBuffer.hasRemaining()){
try{
clientSocket.write(byteBuffer);
}
catch(Exception e){
e.printStackTrace();
}
}
byteBuffer.clear();
}
private String format(String newStringToSend){
if(newStringToSend.equals(null))
return "Default message._EOM";
else if(!newStringToSend.endsWith("_EOM")){
newStringToSend += "_EOM";
return newStringToSend;
}
return newStringToSend;
}
private String readResponse(){
String result = "";
try {
int bytesRead = clientSocket.read(byteBuffer);
byteBuffer.flip();
byte[] data = new byte[bytesRead];
byteBuffer.get(data);
result = new String(data);
}
catch (Exception e){
e.printStackTrace();
}
return result;
}
}