Skip to content

Commit d442f79

Browse files
authored
refactor: improve Socket Client (#2676)
1 parent 9ffe56e commit d442f79

File tree

1 file changed

+11
-12
lines changed

1 file changed

+11
-12
lines changed

app/src/main/java/io/pslab/communication/SocketClient.java

+11-12
Original file line numberDiff line numberDiff line change
@@ -9,23 +9,20 @@
99

1010
public class SocketClient {
1111

12-
public static final String TAG = "SocketClient";
13-
private static SocketClient socketClient = null;
12+
private static final String TAG = SocketClient.class.getSimpleName();
13+
private static SocketClient socketClient;
1414
private Socket socket;
1515
private OutputStream outputStream;
1616
private InputStream inputStream;
1717
private boolean isConnected = false;
1818

19-
public static final int DEFAULT_READ_BUFFER_SIZE = 32 * 1024;
20-
21-
private byte[] buffer = new byte[DEFAULT_READ_BUFFER_SIZE];
22-
2319
private byte[] receivedData;
2420

2521
private SocketClient() {
2622
}
2723

2824
public void openConnection(String ip, int port) throws IOException {
25+
Log.v(TAG, "Connecting to " + ip + ":" + port);
2926
socket = new Socket(ip, port);
3027
outputStream = socket.getOutputStream();
3128
inputStream = socket.getInputStream();
@@ -58,21 +55,23 @@ public synchronized void write(byte[] data) throws IOException {
5855
public synchronized int read(int bytesToBeRead) throws IOException {
5956
int numBytesRead = 0;
6057
int readNow;
61-
Log.v(TAG, "To read : " + bytesToBeRead);
58+
final long start = System.currentTimeMillis();
59+
Log.v(TAG, "Bytes to read : " + bytesToBeRead);
6260
int bytesToBeReadTemp = bytesToBeRead;
63-
receivedData = new byte[DEFAULT_READ_BUFFER_SIZE];
61+
receivedData = new byte[bytesToBeRead];
6462
while (numBytesRead < bytesToBeRead) {
65-
readNow = inputStream.read(buffer, 0, bytesToBeReadTemp);
63+
final long start2 = System.currentTimeMillis();
64+
readNow = inputStream.read(receivedData, numBytesRead, bytesToBeReadTemp);
65+
Log.v(TAG, "Bytes read: " + readNow + " in " + (System.currentTimeMillis() - start2) + " ms");
6666
if (readNow <= 0) {
6767
Log.e(TAG, "Read Error: " + bytesToBeReadTemp);
6868
return numBytesRead;
6969
} else {
70-
System.arraycopy(buffer, 0, receivedData, numBytesRead, readNow);
7170
numBytesRead += readNow;
7271
bytesToBeReadTemp -= readNow;
7372
}
7473
}
75-
Log.v("Bytes Read", "" + numBytesRead);
74+
Log.v(TAG, "Total bytes read: " + numBytesRead + " in " + (System.currentTimeMillis() - start) + " ms");
7675
return numBytesRead;
7776
}
7877

@@ -89,7 +88,7 @@ public void closeConnection() {
8988
isConnected = false;
9089
}
9190
} catch (Exception e) {
92-
e.printStackTrace();
91+
Log.e(TAG, "Error closing connection", e);
9392
}
9493
}
9594
}

0 commit comments

Comments
 (0)