This commit is contained in:
eskimo 2024-10-05 13:36:43 -04:00
parent 4d17f4f56f
commit d5d9395655

View File

@ -91,29 +91,28 @@ public class SocketHandler {
} }
private void receive() { private void receive() {
new Thread(() -> { new Thread(() -> {
try { try {
char[] buffer = new char[1024]; char[] buffer = new char[1024];
StringBuilder messageBuilder = new StringBuilder(); StringBuilder messageBuilder = new StringBuilder();
int numCharsRead; int numCharsRead;
while ((numCharsRead = inputStream.read(buffer)) != -1) { while ((numCharsRead = inputStream.read(buffer)) != -1) {
messageBuilder.append(buffer, 0, numCharsRead); messageBuilder.append(buffer, 0, numCharsRead);
String message = messageBuilder.toString(); String message = messageBuilder.toString();
// Check if the message ends with \r\n (or \n, depending on protocol) // Check if the message ends with \r\n (or \n, depending on protocol)
if (message.endsWith("\r\n")) { if (message.endsWith("\r\n")) {
Log.d("SocketHandler", "Message received: " + message); Log.d("SocketHandler", "Message received: " + message);
delegate.onMessageReceived(id, message); // Notify with full message including \r\n delegate.onMessageReceived(id, message); // Notify with full message including \r\n
messageBuilder.setLength(0); // Clear the buffer for the next message messageBuilder.setLength(0); // Clear the buffer for the next message
}
} }
} catch (IOException e) {
Log.e("SocketHandler", "Receive error: " + e.getMessage(), e);
delegate.onStateChanged(id, "disconnected");
} }
} catch (IOException e) { }).start();
Log.e("SocketHandler", "Receive error: " + e.getMessage(), e); }
delegate.onStateChanged(id, "disconnected");
}
}).start();
}
public interface SocketDelegate { public interface SocketDelegate {
void onStateChanged(String socketId, String state); void onStateChanged(String socketId, String state);