-
Notifications
You must be signed in to change notification settings - Fork 6
/
InputThread.java
75 lines (69 loc) · 2.67 KB
/
InputThread.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
/*
* Curecoin 2.0.0a Source Code
* Copyright (c) 2015 Curecoin Developers
* Distributed under MIT License
* Requires Apache Commons Library
* Supports Java 1.7+
*/
import java.io.*;
import java.net.*;
import java.util.*;
/**
* InputThread only reads data from a peer, and never sends data to prevent blocking and waiting, or some terrible constant back-and-forth keepalive.
* All data read in is stored in an ArrayList<String>, with each line stored independently.
* Data is accessed through a passthrough all the way through PeerNetwork.
*/
public class InputThread extends Thread
{
private Socket socket;
//Private instead of public so that object can control calls to receivedData. Acts as a buffer... the same data shouldn't be read more than once.
private ArrayList<String> receivedData = new ArrayList<String>();
/**
* Constructor to set class socket variable
*/
public InputThread(Socket socket)
{
this.socket = socket;
}
/**
* Constantly reads from the input stream of the socket, and saves any received data to the ArrayList<St
*/
public void run()
{
try
{
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String input;
while ((input = in.readLine()) != null)
{
receivedData.add(input);
//System.out.println("RUN(): " + input);
//System.out.println("size: " + receivedData.size());
}
} catch (Exception e)
{
System.out.println("Peer " + socket.getInetAddress() + " disconnected.");
}
}
/**
* Doesn't actually 'read data' as that's done asynchronously in the threadded run function.
* However, readData is an easy way to think about it--as receivedData acts as a buffer, holding received data until the daemon is ready to handle it.
* Generally, the size of receivedData will be small. However, in some instances (like when downloading many blocks), it can grow quickly.
*
* @return ArrayList<String> Data pulled from receivedData
*/
@SuppressWarnings("unused")
public ArrayList<String> readData()
{
//System.out.println("readData() called!");
//System.out.println("We have " + receivedData.size() + " pieces!");
//Don't want to mess with the ArrayList while run() is modifying it.
ArrayList<String> inputBuffer = new ArrayList<String>(receivedData);
if (inputBuffer == null)
{
inputBuffer = new ArrayList<String>();
}
receivedData = new ArrayList<String>(); //Resets 'buffer'
return inputBuffer;
}
}