} else {
operation = 2;//update hashmap
}
- lc.doLookUp(operation, sock, key);
+ lc.doLookUp(operation, sock, rwkey);
}
}
/** Special character to terminate computation **/
/**
* Call to do a read/ write on socket
**/
- public void doLookUp(int operation, Socket sock, Integer key){
+ public void doLookUp(int operation, Socket sock, int key){
String op;
if (operation == 1) {
- op = new String("r");
- sock.write(op.getBytes());
- sock.write(key.intToByteArray());
+ sock.write(fillBytes(operation, key));
byte b[] = new byte[4];
int numbytes = sock.read(b);
} else {
- op = new String("w");
- sock.write(op.getBytes());
- sock.write(key.intToByteArray());
+ sock.write(fillBytes(operation, key));
}
}
+ /*
+ * Convert int to a byte array
+ **/
+ byte[] fillBytes(int operation, int key) {
+ byte[] b = new byte[5];
+ if(operation == 1) {
+ b[0] = (byte)'r';
+ } else {
+ b[0] = (byte)'w';
+ }
+ for(int i = 1; i < 5; i++){
+ int offset = (3-(i-1)) * 8;
+ b[i] = (byte) ((key >> offset) & 0xFF);
+ }
+ return b;
+ }
+
/**
* Parse the command line options.
**/
public LookUpServerExample(int nobjs, int nthreads) {
this.nobjs = nobjs;
this.nthreads = nthreads;
- System.println("nobjs = "+nobjs+" nthreads= "+nthreads);
}
public static int main(String args[]) {
public static void acceptConnection(ServerSocket ss, HashMap hmap, int nthreads) {
LookUpServerThread[] lus = new LookUpServerThread[nthreads];
- System.println("Here");
for(int i=0; i<nthreads; i++) {
Socket s = ss.accept();
lus[i] = new LookUpServerThread(s, hmap);
for(int i=0; i<nthreads; i++) {
lus[i].join();
}
-
- System.println("Finished");
}
/**
} else {
byte b1[] = new byte[4];
numbytes = sock.read(b1);
- int val = b1[3];
+ int val = getKey(b1);
Integer keyitem = new Integer(val);
/* read from hashmap if opcode sent is "r" */
if(str1.equalsIgnoreCase("r")) {
- doRead(this, keyitem);
+ Integer tmpval = doRead(this, keyitem);
+ //Write object to socket for client
+ sock.write(tmpval.intToByteArray());
} else {
/* update hashmap if opcode sent is "w" */
doUpdate(this, keyitem);
* Synchromize threads accessing hashmap to read key
**/
- synchronized void doRead(LookUpServerThread lusth, Integer key) {
+ synchronized Integer doRead(LookUpServerThread lusth, Integer key) {
//Read object
Object value = lusth.hmap.get(key);
Integer val = (Integer) value;
- //Write object to socket for client
- lusth.sock.write(val.intToByteArray());
- return;
+ return val;
}
/**
Object oldvalue = lusth.hmap.put(key, value);
return;
}
+
+ /*
+ * Convert byte array into int type
+ **/
+
+ int getKey(byte[] b) {
+ int val;
+ val = ((b[0] & 0xFF) << 24) + ((b[1] & 0xFF) << 16) + ((b[2] & 0xFF) << 8) + (b[3] & 0xFF);
+ return val;
+ }
}