Skip to content

refactor: improve Socket Client #2676

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 12, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 11 additions & 12 deletions app/src/main/java/io/pslab/communication/SocketClient.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,20 @@

public class SocketClient {

public static final String TAG = "SocketClient";
private static SocketClient socketClient = null;
private static final String TAG = SocketClient.class.getSimpleName();
private static SocketClient socketClient;
private Socket socket;
private OutputStream outputStream;
private InputStream inputStream;
private boolean isConnected = false;

public static final int DEFAULT_READ_BUFFER_SIZE = 32 * 1024;

private byte[] buffer = new byte[DEFAULT_READ_BUFFER_SIZE];

private byte[] receivedData;

private SocketClient() {
}

public void openConnection(String ip, int port) throws IOException {
Log.v(TAG, "Connecting to " + ip + ":" + port);
socket = new Socket(ip, port);
outputStream = socket.getOutputStream();
inputStream = socket.getInputStream();
Expand Down Expand Up @@ -58,21 +55,23 @@ public synchronized void write(byte[] data) throws IOException {
public synchronized int read(int bytesToBeRead) throws IOException {
int numBytesRead = 0;
int readNow;
Log.v(TAG, "To read : " + bytesToBeRead);
final long start = System.currentTimeMillis();
Log.v(TAG, "Bytes to read : " + bytesToBeRead);
int bytesToBeReadTemp = bytesToBeRead;
receivedData = new byte[DEFAULT_READ_BUFFER_SIZE];
receivedData = new byte[bytesToBeRead];
while (numBytesRead < bytesToBeRead) {
readNow = inputStream.read(buffer, 0, bytesToBeReadTemp);
final long start2 = System.currentTimeMillis();
readNow = inputStream.read(receivedData, numBytesRead, bytesToBeReadTemp);
Log.v(TAG, "Bytes read: " + readNow + " in " + (System.currentTimeMillis() - start2) + " ms");
if (readNow <= 0) {
Log.e(TAG, "Read Error: " + bytesToBeReadTemp);
return numBytesRead;
} else {
System.arraycopy(buffer, 0, receivedData, numBytesRead, readNow);
numBytesRead += readNow;
bytesToBeReadTemp -= readNow;
}
}
Log.v("Bytes Read", "" + numBytesRead);
Log.v(TAG, "Total bytes read: " + numBytesRead + " in " + (System.currentTimeMillis() - start) + " ms");
return numBytesRead;
}

Expand All @@ -89,7 +88,7 @@ public void closeConnection() {
isConnected = false;
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Error closing connection", e);
}
}
}