Moved calculation of "numChunks" in Util class

This commit is contained in:
senft-lap 2012-11-09 22:32:42 +01:00
parent 74cdefa6f8
commit abe06ca827
3 changed files with 41 additions and 7 deletions

View File

@ -6,6 +6,7 @@ import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import common.MessageType;
import common.Util;
public class BufferedNetworkStackClient {
protected static final long TIMEOUT = 5000;
@ -59,13 +60,9 @@ public class BufferedNetworkStackClient {
private void sendChunks(String s, InetSocketAddress dest, int bufSize,
int sessionId) {
// The amount of actual data we can store in a packet
int lenData = bufSize - 9;
int lenData = Util.actualData(bufSize);
// Number of chunks needed to send 's'. We use bufSize-9 because the
// first 9 bytes of each packet are metadata (message_type, session_id,
// chunk_id).
int numChunks = (int) Math.ceil((s.length() * 1.0 / lenData));
int numChunks = Util.numChunks(bufSize, s.length());
for (int chunkId = 0; chunkId < numChunks; chunkId++) {
buf.flip();

View File

@ -0,0 +1,33 @@
package common;
public class Util {
/**
* Calculates how many chunks are needed to send a message.
*
* @param bufSize
* The buffer size of the receiver
* @param length
* The length of the data
* @return The number of chunks needed
*/
public static int numChunks(int bufSize, int length) {
/*
* We have to do bufSize - 9 here, because we have 9 bytes of meta data
* in every packet.
*/
return (int) Math.ceil(length * 1.0 / actualData(bufSize));
}
/**
* Calculates how much actual data a packet can store when sending to a
* specific host.
*
* @param bufSize
* The buffer size of the receiver
* @return The number of bytes
*/
public static int actualData(int bufSize) {
return bufSize - 9;
}
}

View File

@ -10,6 +10,7 @@ import java.util.EmptyStackException;
import java.util.Stack;
import common.MessageType;
import common.Util;
class BufferedNetworkStack {
@ -87,7 +88,10 @@ class BufferedNetworkStack {
int size = buf.getInt();
int id = temp.size();
temp.add(id, new Element(size, id));
int numChunks = Util.numChunks(BUF_SIZE, size);
temp.add(id, new Element(numChunks, id));
buf.flip();
buf.clear();