/** Sending and receiving data by the socket */ @Override void handle_poll_activity(int timeout) { if (!socket_.isConnected()) { Log.d(TAG, "Socket is not connected"); break_contact(ContactEvent.reason_t.BROKEN); } // if we have something to send , send it first if (sendbuf_.position() > 0) send_data(); // poll to receive and process data try { num_to_read_ = read_stream_.available(); // check that there's something to read if (num_to_read_ > 0) { Log.d(TAG, "before reading position is " + recvbuf_.position()); java.nio.ByteBuffer temp_java_nio_buf = java.nio.ByteBuffer.allocate(recvbuf_.remaining()); read_channel_.read(temp_java_nio_buf); BufferHelper.copy_data( recvbuf_, recvbuf_.position(), temp_java_nio_buf, 0, temp_java_nio_buf.position()); recvbuf_.position(recvbuf_.position() + temp_java_nio_buf.position()); if (DTNService.is_test_data_logging()) TestDataLogger.getInstance() .set_downloaded_size( TestDataLogger.getInstance().downloaded_size() + temp_java_nio_buf.position()); Log.d(TAG, "buffer position now is " + recvbuf_.position()); process_data(); if (recvbuf_.remaining() == 0) { Log.e(TAG, "after process_data left no space in recvbuf!!"); } } } catch (IOException e) { Log.e(TAG, "IOException, in reading data from the read_stream_:" + e.getMessage()); } // send keep alive message if we should send it if (contact_up_ && !contact_broken_) { check_keepalive(); } if (!contact_broken_) check_timeout(); }
@Override void send_data() { int last_position = sendbuf_.position(); sendbuf_.rewind(); try { Log.d(TAG, "Going to write " + last_position + " bytes to the stream"); java.nio.ByteBuffer temp = java.nio.ByteBuffer.allocate(last_position); BufferHelper.copy_data(temp, 0, sendbuf_, 0, last_position); WriteSocketTimeoutTimer write_socket_timeout_timer = new WriteSocketTimeoutTimer(write_channel_); Log.d(TAG, "scheduling write_timeout_task in " + SOCKET_TIMEOUT + " seconds"); try { // add the timer to keep looking for Socket timeout write_socket_timeout_timer.schedule_in(SOCKET_TIMEOUT); } catch (IllegalStateException e) { Log.e(TAG, "write socket timer stop when it shouldn't be stopped"); } write_channel_.write(temp); // cancel the timer if it's come here, this means the writting is // successful write_socket_timeout_timer.cancel(); write_socket_timeout_timer = null; // move the remaining data back to beginning for next writting // the position of the buffer will be moved to the newly available // position after movement sendbuf_.rewind(); if (DTNService.is_test_data_logging()) TestDataLogger.getInstance() .set_uploaded_size(TestDataLogger.getInstance().uploaded_size() + last_position); } catch (AsynchronousCloseException e) { Log.e(TAG, "another thread close the channel because of the timeout"); break_contact(reason_t.CL_ERROR); sendbuf_.position(last_position); } catch (IOException e) { Log.e(TAG, "writting broken pipe"); break_contact(reason_t.CL_ERROR); sendbuf_.position(last_position); } }