-
Notifications
You must be signed in to change notification settings - Fork 1
/
MessageHandler.java
261 lines (244 loc) · 13 KB
/
MessageHandler.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
import jdk.jshell.execution.Util;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicReference;
public class MessageHandler implements Runnable {
public peerProcess myProcess;
public ConcurrentLinkedQueue<Message> messageQueue;
public ConcurrentHashMap<String, TCPConnectionInfo> peersToTCPConnectionsMapping;
public HashSet<Integer> requestedPieces;
public HashSet<Integer> receivedPieces;
MessageHandler(peerProcess myProcess) {
this.myProcess = myProcess;
this.peersToTCPConnectionsMapping = myProcess.peersToTCPConnectionsMapping;
this.messageQueue = myProcess.messageQueue;
this.requestedPieces = new HashSet<>();
this.receivedPieces = new HashSet<>();
}
/**
* Each of the below CreateAndSend<MessageType>Message() function creates a message object with the required fields.
* Then it sends the message to corresponding peer through the TCPConnection.
*/
private void CreateAndSendBitFieldMessage(TCPConnectionInfo associatedTCPConnection) {
try {
if (associatedTCPConnection.isAlive()) {
Message bitFieldMessage = new Message((byte) 5, 1 + myProcess.myBitField.length, myProcess.myBitField);
associatedTCPConnection.sendMessage(bitFieldMessage);
}
} catch (NullPointerException | IOException ex) {
}
}
private void CreateAndSendHaveMessage(TCPConnectionInfo associatedTCPConnection, int pieceID) {
// Have message
try {
if (associatedTCPConnection.isAlive()) {
Message haveMessage = new Message((byte) 4, 5, pieceID);
associatedTCPConnection.sendMessage(haveMessage);
}
} catch (NullPointerException | IOException ex) {
}
}
private void CreateAndSendRequestMessage(TCPConnectionInfo associatedTCPConnection, int pieceID) {
try {
if (associatedTCPConnection.isAlive()) {
Message requestMessage = new Message((byte) 6, 5, pieceID);
associatedTCPConnection.sendMessage(requestMessage);
}
} catch (NullPointerException | IOException ex) {
}
}
private void CreateAndSendInterestedMessage(TCPConnectionInfo associatedTCPConnection) {
try {
if (associatedTCPConnection.isAlive()) {
Message interestedMessage = new Message((byte) 2, 1);
associatedTCPConnection.sendMessage(interestedMessage);
}
} catch (NullPointerException | IOException ex) {
}
}
private void CreateAndSendNotInterestedMessage(TCPConnectionInfo associatedTCPConnection) {
try {
if (associatedTCPConnection.isAlive()) {
Message notInterestedMessage = new Message((byte) 3, 1);
associatedTCPConnection.sendMessage(notInterestedMessage);
}
} catch (NullPointerException | IOException ex) {
}
}
protected void CreateAndSendChokeMessage(TCPConnectionInfo associatedTCPConnection) {
try {
if (associatedTCPConnection.isAlive()) {
Message chokeMessage = new Message((byte) 0, 1);
associatedTCPConnection.sendMessage(chokeMessage);
}
} catch (NullPointerException | IOException ex) {
}
}
protected void CreateAndSendUnchokeMessage(TCPConnectionInfo associatedTCPConnection) {
try {
if (associatedTCPConnection.isAlive()) {
Message unChokeMessage = new Message((byte) 1, 1);
associatedTCPConnection.sendMessage(unChokeMessage);
}
} catch (NullPointerException | IOException ex) {
}
}
private void CreateAndSendPieceMessage(TCPConnectionInfo associatedTCPConnection, int pieceIndex, byte[] piece) {
try {
if (associatedTCPConnection.isAlive()) {
Message pieceMessage = new Message((byte) 7, 5 + myProcess.pieceSize, pieceIndex, piece);
associatedTCPConnection.sendMessage(pieceMessage);
}
} catch (NullPointerException | IOException ex) {
}
}
private int getARandomInterestingPiece(String associatedPeer) {
boolean[] bitField = myProcess.bitFieldsOfPeers.get(associatedPeer);
ArrayList<Integer> interestingPieces = new ArrayList<>();
for (int pieceIndex = 1; pieceIndex <= myProcess.numberOfPieces; pieceIndex++) {
if (!myProcess.myBitField[pieceIndex - 1] && bitField[pieceIndex - 1] && !myProcess.requestedPieces.contains(pieceIndex)) {
interestingPieces.add(pieceIndex);
}
}
if (interestingPieces.size() == 0) {
return -1;
}
Random random = new Random();
int requestPiece;
do {
int randomIndex = random.nextInt(interestingPieces.size());
requestPiece = interestingPieces.get(randomIndex);
} while (myProcess.requestedPieces.contains(requestPiece) || myProcess.downloadedPieces.contains(requestPiece));
return requestPiece;
}
public void run() {
while (!Thread.interrupted()) {
if (!messageQueue.isEmpty()) {
Message newMessage = messageQueue.remove();
String peerId = newMessage.messageOrigin.associatedPeerId;
switch (newMessage.messageType) {
case 0:
//Handle Choke message
peerProcess.logger.writeLog(LogMessage.CHOKING, new String[]{peerId});
myProcess.canRequestStatus.put(peerId, false);
break;
case 1:
//Handle Unchoke message
peerProcess.logger.writeLog(LogMessage.UNCHOKING, new String[]{peerId});
if (!myProcess.canRequestStatus.get(peerId)) {
myProcess.canRequestStatus.put(peerId, true);
int requestPiece = getARandomInterestingPiece(peerId);
if (requestPiece > 0 && !myProcess.requestedPieces.contains(requestPiece)) {
myProcess.requestedPieces.add(requestPiece);
CreateAndSendRequestMessage(newMessage.messageOrigin, requestPiece);
}
}
break;
case 2:
//Handle Interested message
peerProcess.logger.writeLog(LogMessage.RECEIVE_INTERESTED,new String[]{peerId});
if (myProcess.peerInfoMap.containsKey(peerId)) {
if (!myProcess.interestedPeers.contains(peerId))
myProcess.interestedPeers.add(peerId);
}
break;
case 3:
//Handle Not interested message
peerProcess.logger.writeLog(LogMessage.RECEIVE_NOT_INTERESTED,new String[]{peerId});
myProcess.interestedPeers.remove(peerId);
break;
case 4:
//Handle Have message
//Update the associatedPeerBitfield
int pieceIndex = newMessage.pieceIndex;
peerProcess.logger.writeLog(LogMessage.RECEIVE_HAVE, new String[]{peerId, Integer.toString(pieceIndex)});
boolean[] currentBitField = myProcess.bitFieldsOfPeers.get(peerId);
currentBitField[pieceIndex - 1] = true;
myProcess.bitFieldsOfPeers.put(peerId, currentBitField);
//Check if you are interested in this piece.
if (!myProcess.myBitField[pieceIndex - 1]) {
CreateAndSendInterestedMessage(newMessage.messageOrigin);
} else {
CreateAndSendNotInterestedMessage(newMessage.messageOrigin);
}
break;
case 5:
//Handle bitfield message
String connectedPeer = newMessage.messageOrigin.associatedPeerId;
boolean interested = false;
System.out.println("Received BitField Message from PEER: "+connectedPeer);
for (int i = 0; i < myProcess.numberOfPieces; i++) {
if (newMessage.bitField[i] && !myProcess.myBitField[i]) {
interested = true;
break;
}
}
if (interested) {
CreateAndSendInterestedMessage(newMessage.messageOrigin);
} else {
CreateAndSendNotInterestedMessage(newMessage.messageOrigin);
}
myProcess.bitFieldsOfPeers.put(connectedPeer, newMessage.bitField);
break;
case 6:
//Handle request message
int requestedPiece = newMessage.pieceIndex;
System.out.println("Received Request Message from PEER: "+peerId+" for piece: "+requestedPiece);
if (myProcess.unchokeStatus.get(peerId) && requestedPiece > 0 && requestedPiece <= myProcess.numberOfPieces) {
int pieceSize = myProcess.pieceSize;
if (requestedPiece == myProcess.numberOfPieces) {
pieceSize = myProcess.lastPieceSize;
}
byte[] piece = myProcess.myFileObject.readPiece(requestedPiece, pieceSize);
CreateAndSendPieceMessage(newMessage.messageOrigin, requestedPiece, piece);
}
break;
case 7:
//Handle Piece message
pieceIndex = newMessage.pieceIndex;
if (!myProcess.downloadedPieces.contains(pieceIndex)) {
int offset = (pieceIndex - 1) * myProcess.pieceSize;
int pieceSize = myProcess.pieceSize;
if (pieceIndex == myProcess.numberOfPieces) {
pieceSize = myProcess.lastPieceSize;
}
boolean pieceDownloaded = myProcess.myFileObject.writePiece(pieceIndex, newMessage.piece, pieceSize);
if (pieceDownloaded) {
//update bitField
myProcess.downloadedPieces.add(pieceIndex);
peerProcess.logger.writeLog(LogMessage.PIECE_DOWNLOAD,new String[]{peerId,Integer.toString(pieceIndex),Integer.toString(myProcess.downloadedPieces.size())});
myProcess.downloadRate.put(peerId, myProcess.downloadRate.get(peerId) + 1);
// System.out.println("Received " + myProcess.downloadedPieces.size() + " pieces out of " + myProcess.numberOfPieces + " pieces");
// System.out.println("Requested " + myProcess.requestedPieces.size() + " pieces out of " + myProcess.numberOfPieces + " pieces");
myProcess.myBitField[pieceIndex - 1] = true;
for (TCPConnectionInfo conn : myProcess.peersToTCPConnectionsMapping.values()) {
CreateAndSendHaveMessage(conn, pieceIndex);
}
if (myProcess.canRequestStatus.get(peerId)) {
int requestPiece = getARandomInterestingPiece(peerId);
if (requestPiece > 0) {
myProcess.requestedPieces.add(requestPiece);
CreateAndSendRequestMessage(newMessage.messageOrigin, requestPiece);
}
}
}
}
break;
case 100:
System.out.println("Received Handshake Message from PEER:"+peerId);
//Handle Handshake message
if(peerId.compareTo(myProcess.peerId)>0) {
peerProcess.logger.writeLog(LogMessage.CLIENT_CONNECT, new String[]{peerId});
}else{
peerProcess.logger.writeLog(LogMessage.SERVER_CONNECT, new String[]{peerId});
}
CreateAndSendBitFieldMessage(newMessage.messageOrigin);
break;
default:
}
}
}
}
}